Home >Web Front-end >JS Tutorial >How to modify element attributes in javascript
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.
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()
Element object.setAttribute('attribute','attribute value');
<div>hello</div> <div id="box">欢迎来到PHP中文网!</div> <script type="text/javascript"> var box=document.getElementById("box"); box.setAttribute('style','color:red;border:1px solid #008000'); // 给box元素设置的是行内样式 </script>Rendering:
Method 2: Modify directly through the style object of the element node
element Object.style.Attribute name='attribute value';
<div>hello</div> <div id="box">欢迎来到PHP中文网!</div> <script type="text/javascript"> var box=document.getElementById("box"); box.style.color='#fff'; box.style.backgroundColor='#ff6c8c'; box.style.padding='10px'; </script>Rendering:
Method 3: Use cssText attribute
Syntax:Element object.style.cssText='Attribute name:Attribute value;';
<div>hello</div> <div id="box">欢迎来到PHP中文网!</div> <script type="text/javascript"> var box=document.getElementById("box"); box.style.cssText='color:#fff;background-color:#ffaa00;padding:10px;'; </script>Rendering: [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!