简体   繁体   中英

Traverse and return html tags in javascript

Lets say I've this HTML code:

<div>
    <h2>You know, I am a Heading!</h2>
    <ul>
        <li>I am the first li</li>
        <li>I am the second li</li>
        <li>I am the third li</li>
    </ul>
</div>

<button onclick="go()" style="width:100px">Go!</button>

On the press of "Go!" button, the JavaScript would be called that would return me the node elements of the DOM.

<script>     
function go() {
  var childNodes = document.body.childNodes;
  for(var i=0; i<childNodes.length; i++) {
    var domElement = childNodes[i];
            doSomethingWithTheReturnedTag(); 
  }
}
</script>

What exactly I'm trying to do is when the button is clicked, my script goes through the entire HTML document and get each tag and perform an operation on the returned tag.

Just need suggestions if at all this is possible or there is some better approach to do it?

Thanks in advance!

To loop over all DOM elements:

  <script>     
    function go() {
    var items = startElem.getElementsByTagName("*");
    for (var i = items.length; i--;) {
       //perform operation on elment
    }
    }
 </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM