JavaScript获取DOM节点

常用的方法有

document.getElementById("id");
document.getElementsByTagName('tagName');
document.getElementsByName('inputName');
document.getElementByClassName('className');

 其中只有通过id才能保证获得是一个元素。其他的方法获得的都是一个集合(collection),可以使用数组的访问方式访问。

下面是简单的实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .span_class_1{background: red}
        .span_class_2{background: orange}
    </style>
</head>
<body>
    <div id="div_id">this is tag div</div>

    <p>this is tag p1</p><br>
    <p>this is tag p2</p><br>
    <p>this is tag p3</p><br>

    <span class="span_class_1">this is tag span1</span><br>
    <span class="span_class_1">this is tag span2</span><br>

    <input type="text" name="username"><br>
    <input type="text" name="age"><br>
</body>
    <script>
        var div=document.getElementById("div_id");
        console.log(div.innerHTML);

        var p=document.getElementsByTagName("p");
        console.log(p[0].innerHTML);
        console.log(p[2].innerHTML);

        var span=document.getElementsByClassName("span_class_1");
        console.log(span[1].innerHTML);

        var input=document.getElementsByName("username");
        console.log(input[0].innerHTML);
    </script>
</html>
原文地址:https://www.cnblogs.com/-beyond/p/7918727.html