js 元素操作

1.获取同名元素  document.getElementsByName("myInput");

<html>
<head>
<script type="text/javascript">
function getElements()
  {
  var x=document.getElementsByName("myInput");
  alert(x.length);
  }
</script>
</head>

<body>
<input name="myInput" type="text" size="20" /><br />
<input name="myInput" type="text" size="20" /><br />
<input name="myInput" type="text" size="20" /><br />
<br />
<input type="button" onclick="getElements()" value="名为 'myInput' 的元素有多少个?" />
</body>

</html>

2.根据html元素的class name获取元素 

参考Document.getElementsByClassName()

<html>
<body>
    <div id="parent-id">
        <p>hello world 1</p>
        <p class="test">hello world 2</p>
        <p>hello world 3</p>
        <p>hello world 4</p>
    </div>

    <script>
        var parentDOM = document.getElementById("parent-id");
        
        var test = parentDOM.getElementsByClassName("test"); // a list of matching elements, *not* the element itself
        console.log(test); //HTMLCollection[1]

        var testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted
        console.log(testTarget); //<p class="test">hello world 2</p>
    </script>
</body>
</html>

 

posted on 2020-02-26 11:00  dreamstar  阅读(88)  评论(0编辑  收藏  举报