JS遍历/获取当前页面中所有HTML元素


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demo-js-all</title>
</head>
<body>


<script type="text/javascript">
function allElements(){
    var x='(';
    var len=document.all.length;
    var allx=document.all;
    for(var i=0;i<len;i++){
        x+=allx.item(i).tagName;
        x+=',';
        x+=allx.item(i).name;
        x+=') (';
        x=x.replace(',undefined','');
    }
    x+=')';
    x=x.replace('()','');
    document.Form1.content.value=x;
}

function allForms(){
    var x='(';
    var forms=document.getElementsByTagName('form');
    var len=forms.length;
    for(var i=0;i<len;i++){
        x+=forms.item(i).tagName;
        x+=',';
        x+=forms.item(i).name;
        x+=') (';
    }
    x+=')';
    x=x.replace('()','');
    document.Form1.content.value=x;
}

function allButtons(){
    var x='(';
    var buttons=document.getElementsByTagName('button');
    var len=buttons.length;
    for(var i=0;i<len;i++){
        x+=buttons.item(i).tagName;
        x+=',';
        x+=buttons.item(i).name;
        x+=') (';
    }
    x+=')';
    x=x.replace('()','');
    document.Form1.content.value=x;
}
console.log(document.all);//
</script>


<form name="Form1">
  <textarea name="content" cols="99" rows="9"></textarea>
</form>
<form name="Form2">
</form>
<form name="Form3">
</form>
<br />

<button name="allElements" onclick="allElements()" type="button">当前页面中所有HTML元素</button>

<button name="allForms" onclick="allForms()" type="button">当前页面中所有form元素</button>

<button name="allButtons" onclick="allButtons()" type="button">当前页面中所有button元素</button>


<table>
  <tr>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
  </tr>
</table>


</body>
</html>

程序运行结果如下,点击这里亲自运行看看