首页 > 编程语言 >javascript:innerText、innerHTML、textContent的区别(chrome 107.0.5304.62)

javascript:innerText、innerHTML、textContent的区别(chrome 107.0.5304.62)

时间:2022-10-28 10:25:33浏览次数:77  
标签:chrome 107.0 textContent innerHTML getElementById innerText let document

一,js代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>innerText、innerHTML、textContent的区别</title>
</head>
<body>
    <!--演示输出内容的区别-->
    <button onclick="out()">输出内容</button>
    <div id="out1"></div>
    <div id="out2"></div>
    <div id="out3"></div>

    <!--演示获取内容的区别-->
    <hr/>
    原始内容:<div id="get1">
        <div>
           <span class="title">hello</span>,i am <span style='color:#ff0000;'>laoliu</span>
        </div>
        <div style="display: none;">
            中文名:老刘
        </div>
        <style>
            .title {
                font-size: 30px;
            }
        </style>
        <script>
            function hello() {
                alert("老刘厉害了!");
            }
        </script>
        </div>
    <button onclick="get()">获取内容</button>
    
    <div id="set1"></div>
    <div id="set2"></div>
    <div id="set3"></div>
    <script type="text/javascript">
        //例1:输出时 innerText 和 textContent 不会对html标签进行解析,而是当做纯文本内容显示出来
        //innerHTML可以对html标签解析
        function out() {
            let out1 = document.getElementById('out1');
            let out2 = document.getElementById('out2');
            let out3 = document.getElementById('out3');

            let cont = "hello,i am <span id='nameSpan' style='color:#ff0000;'>laoliu</span>";
            out1.innerText = cont;
            out2.innerHTML = cont;
            out3.textContent = cont;

            let nameSpan = document.getElementById('nameSpan');
            alert("新生成的nameSpan的内容:"+nameSpan.innerHTML);
        }

        //例2:获取内容时,innerText 和 textContent 会去掉html标签,
        //innerHTML会保留html标签
        //innerText会忽略display:none的内容,而textContent会获取此内容
        //textContent会获取style和script标签的内容,而innerText会忽略
        function get() {
            let get1 = document.getElementById('get1');

            let set1 = document.getElementById('set1');
            let set2 = document.getElementById('set2');
            let set3 = document.getElementById('set3');
            set1.innerText = get1.innerText;
            set2.innerHTML = get1.innerHTML;
            set3.textContent = get1.textContent;
        }

    </script>
</body>
</html>

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: [email protected]

二,测试效果

三,查看chrome浏览器的版本:

 

标签:chrome,107.0,textContent,innerHTML,getElementById,innerText,let,document
From: https://www.cnblogs.com/architectforest/p/16834925.html

相关文章