Once we get a DOM node, we can update it.
You can modify the text of a node directly by two ways:
One is to modify the innerHTML
property, which is very powerful, not only to modify the text content of a DOM node, but also to modify the subtree inside the DOM node directly from the HTML fragment:
// 获取<p id="p-id">...</p>var p = document.getElementById(‘p-id‘);// 设置文本为abc:p.innerHTML = ‘ABC‘; // <p id="p-id">ABC</p>// 设置HTML:p.innerHTML = ‘ABC <span style="color:red">RED</span> XYZ‘;// <p>...</p>的内部结构已修改
innerHTML
when using, be aware that you need to write HTML. If the string is written over the network, pay attention to character encoding to avoid XSS attacks.
The second is a modification innerText
or textContent
attribute that automatically encodes the string so that no HTML tags can be set:
// 获取<p id="p-id">...</p>var p = document.getElementById(‘p-id‘);// 设置文本:p.innerText = ‘<script>alert("Hi")</script>‘;// HTML被自动编码,无法设置一个<script>节点:// <p id="p-id"><script>alert("Hi")</script></p>
The difference between the two is that when the property is read, the innerText
text of the hidden element is not returned, and textContent
all the text is returned. Also note that ie<9 is not supported textContent
.
Modifying CSS is also a frequently needed operation. The properties of the DOM node style
correspond to all of the CSS, which can be directly obtained or set. Because CSS allows font-size
such a name, it is not a valid JavaScript property name, so it needs to be rewritten in JavaScript as a camel-named fontSize
:
// 获取<p id="p-id">...</p>var p = document.getElementById(‘p-id‘);// 设置CSS:p.style.color = ‘#ff0000‘;p.style.fontSize = ‘20px‘;p.style.paddingTop = ‘2em‘;
Practice
Like the following HTML structure:
Javascript
Java
<!-- HTML结构 --><div id="test-div"> <p id="test-js">javascript</p> <p>Java</p></div>
Please try to get the specified node and modify:
Get <p>javascript</p> node:
var js = document.getElementById (' Test-js ');
Modify the text to JavaScript:
Todo:
Js.innerhtml= ' JavaScript ';
Modify CSS to: color: #ff0000, Font-weight:bold
Todo:
Js.style.color= ' #ff0000 ';
Js.style.fontweight= ' Bold ';
Liaoche JS Tutorial Note 12 updating INNERHMTL and modifying CSS styles with DOM