HTML DOM-->获取标签(元素)节点

1.根据元素id获取元素节点:

  document.getElementById(str)

  举例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>
        <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body style="height: 187.5rem;">
        <div id="box">这个一个div</div>
        <script type="text/javascript">
            var jsDiv = document.getElementById('box')
            console.log(jsDiv)
            console.log(typeof(jsDiv))
        </script>
    </body>
</html>

  输出:

 

2.获取相同class属性的元素节点列表

  document.getElementsByClassName()

  注意:此方法不支持IE8以下

  举例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>
        <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body style="height: 187.5rem;">
        <div class="box1">screen</div>
        <div class="box2">verse</div>
        <div class="box2">take</div>
        <script type="text/javascript">
            var js = document.getElementsByClassName('box2')
            console.log(js)
            console.log(typeof(js))
        </script>
    </body>
</html>

  输出:

 

3.根据标签名来获取元素节点的集合

  getElementsByTagName()

  举例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>
        <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body style="height: 187.5rem;">
        <div class="box1">screen</div>
        <div class="box2">verse</div>
        <div class="box2">take</div>
        <script type="text/javascript">
            var js = document.getElementsByTagName('div')
            console.log(js)
            console.log(typeof(js))
        </script>
    </body>
</html>

  输出:

 

4.根据name属性值来获取元素节点的集合

  document.getElementsByName('name_value')

  举例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>
        <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body style="height: 187.5rem;">
        <input type="text" name="Text">
        <input type="text" name="Text">
        <input type="text" name="Text">
        <script type="text/javascript">
            var js = document.getElementsByName('Text')
            console.log(js)
            console.log(typeof(js))
        </script>
    </body>
</html>

  输出:

posted @ 2020-04-17 21:20  abner_pan  阅读(2062)  评论(0编辑  收藏  举报