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

伊谢尔伦
Release: 2017-07-20 13:24:07
Original
2017 people have browsed it

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);//测试
Copy after login

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');
Copy after login

It is very easy to change the properties of this element. We can change innerHTML.


my.innerHTML = 'final';//final
Copy after login

Because innerHTML can write html, so let's modify html.


my.innerHTML = &#39;<em>my</em> final&#39;;//<em>my</em> fnal
Copy after login

em tag has become part of the dom tree. We can test it


my.firstChild;//<em> 
my.firstChild.firstChild;//my
Copy after login

We can also change the value through nodeValue.


my.firstChild.firstChild.nodeValue = &#39;your&#39;;//your
Copy after login

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";
Copy after login

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;;
Copy after login

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;">
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template