简体   繁体   English

遍历并返回javascript中的html标签

[英]Traverse and return html tags in javascript

Lets say I've this HTML code: 可以说我有以下HTML代码:

<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. 按钮,将调用JavaScript,该JavaScript将返回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. 我要尝试做的就是单击按钮时,脚本会遍历整个HTML文档并获取每个标签,并对返回的标签执行操作。

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: 要遍历所有DOM元素:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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