Home  >  Article  >  Web Front-end  >  How to modify element attributes in javascript

How to modify element attributes in javascript

青灯夜游
青灯夜游Original
2021-10-13 11:51:5812999browse

JS method to modify element attributes: 1. Use the "element object.setAttribute('attribute','attribute value')" statement; 2. Use "element object.style.Attribute name='attribute value' " statement; 3. Use the "element object.style.cssText='Attribute name: attribute value;'" statement.

How to modify element attributes in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript to modify the attributes of elements

Method 1: Use setAttribute()

## The #setAttribute() method adds the specified attribute and assigns it the specified value. If this specified property already exists, the value is only set/changed.

Syntax:

Element object.setAttribute('attribute','attribute value');

Example:

<div>hello</div> 
<div id="box">欢迎来到PHP中文网!</div> 
<script type="text/javascript">
	var box=document.getElementById("box");
	box.setAttribute(&#39;style&#39;,&#39;color:red;border:1px solid #008000&#39;);
	// 给box元素设置的是行内样式
</script>

Rendering:


How to modify element attributes in javascript

Method 2: Modify directly through the style object of the element node

Syntax:

element Object.style.Attribute name='attribute value';

Example:

<div>hello</div> 
<div id="box">欢迎来到PHP中文网!</div> 
<script type="text/javascript">
	var box=document.getElementById("box");
	box.style.color=&#39;#fff&#39;;
	box.style.backgroundColor=&#39;#ff6c8c&#39;;
	box.style.padding=&#39;10px&#39;;
</script>

Rendering:

How to modify element attributes in javascript

Method 3: Use cssText attribute

Syntax:

Element object.style.cssText='Attribute name:Attribute value;';

Example:

<div>hello</div> 
<div id="box">欢迎来到PHP中文网!</div> 
<script type="text/javascript">
	var box=document.getElementById("box");
	box.style.cssText=&#39;color:#fff;background-color:#ffaa00;padding:10px;&#39;;
</script>

Rendering:

How to modify element attributes in javascript

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to modify element attributes in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn