DOM获取元素内容三种方法及其区别

2019-07-01  本文已影响0人  好名字都让你们用了

1:获取元素内的内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <style>
        button{
            border:1px solid red;
        }
    </style>
    <div class="contain">
        北京上海广州<span>深圳厦门</span>陕西西安
        <p>台湾香港澳门</p>
    </div>
    <button onclick="myFunction()">我是按钮</button>
    <script>
        function myFunction(){
            console.log(event.type);
        }
        var container = document.querySelector("body");
        console.log("textContent的内容是:",container.textContent);
        console.log("innerText的内容是:",container.innerText);
        console.log("innerHTML的内容是:",container.innerHTML);
    </script>
</body>
</html>

1:通过textContent属性可以获取指定节点的文本,以及该指定节点所包含后代节点中文本内容,也包含style中的内容

textContent中的内容是:
        button{
            border:1px solid red;
}
     北京上海广州深圳厦门陕西西安台湾香港澳门
我是按钮
script中的内容

2:IE引入了node.innerText属性,该属性会获取指定节点的文本以及后代节点中的文本,不会获取style和script中的内容

innerText中的内容是: 北京上海广州深圳厦门陕西西安台湾香港澳门
我是按钮

3:innerHTML就是获取指定元素内的HTML内容

就是body标签中的内容都能获取
上一篇 下一篇

猜你喜欢

热点阅读