Home >Web Front-end >JS Tutorial >Detailed explanation of how to traverse and modify dom instances in JavaScript

Detailed explanation of how to traverse and modify dom instances in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-20 13:24:072014browse

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 = &#39;<em>my</em> final&#39;;//<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 = &#39;your&#39;;//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 = &#39;bold&#39;;

We can also modify other properties, whether these properties are initialized or not.


my.align = "right"; 
my.name = &#39;myname&#39;; 
my.id = &#39;further&#39;; 
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!

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