Home >Web Front-end >JS Tutorial >Detailed explanation of how to traverse and modify dom instances in JavaScript
Traverse DOM
We can write a function to traverse DOM
function walkDOM(n) { do { alert(n); if (n.hasChildNodes()) { walkDOM(n.firstChild) } } while (n = n.nextSibling) } walkDOM(document.body);//测试
Modify nodes
Let’s take a look at the modification of DOM nodes.
First get the node to be changed.
var my = document.getElementById('closer');
It is very easy to change the properties of this element. We can change innerHTML.
my.innerHTML = 'final';//final
Because innerHTML can write html, so let's modify html.
my.innerHTML = '<em>my</em> final';//<em>my</em> fnal
em tag has become part of the dom tree. We can test it
my.firstChild;//<em> my.firstChild.firstChild;//my
We can also change the value through nodeValue.
my.firstChild.firstChild.nodeValue = 'your';//your
Modify style
Most of the modified nodes may be modified styles. Element nodes have the style attribute to modify the style. There is a one-to-one correspondence between style attributes and css attributes. The following code
my.style.border = "1px solid red";
Many CSS attributes have dashes ("-"), such as padding-top, which is illegal in javascript. In this case, be sure to omit the tilde and capitalize the first letter of the second word, as follows. margin-left becomes marginLeft. And so on
my.style.fontWeight = 'bold';
We can also modify other properties, whether these properties are initialized or not.
my.align = "right"; my.name = 'myname'; my.id = 'further'; my;//<p id="further" align="right" style="border: 1px solid red; font-weight: bold;">
The above is the detailed content of Detailed explanation of how to traverse and modify dom instances in JavaScript. For more information, please follow other related articles on the PHP Chinese website!