JS中的innerHTML和innerText

        今天在进行DOM总结的时候遇到了innerHTML,由于在前几天看到了小伙伴总结了一篇关于innerHTML和innerText的博客总结,于是自己也开始搜查资料做一个小小的总结。

       1.innerHTML可获取或设置指定dom元素标签内的 html内容,从该元素标签的起始位置到终止位置的全部内容(包含html标签)。

获取元素的内容:element.innerHTML;

给元素设置内容:element.innerHTML =htmlString;

        2.innerText可获取或设置指定元素标签内的文本值,从该元素标签的起始位置到终止位置的全部文本内容(不包含html标签)。

获取元素的内容:element.innerText;

给元素设置内容:element.innerText = string;

        3.区别

innerHTML返回的是标签内的 html内容,包含html标签;

innerText返回的是标签内的文本值,不包含html标签;

        实例:【获取元素内容】

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>

    <script type="text/javascript">
        function getinnerHTML() {
            alert( document.getElementById("test").innerHTML);
        }
        function getinnerText() {
            alert( document.getElementById("test").innerText);
        }
    </script>
</head>
<body>

    <p id="test"><font color="#000">获取段落p的innerHTML</font></p>
    <!--//给按钮一个单机事件-->
    <input type="button" onclick="getinnerHTML()" value="innerHTML" />
    <input type="button" onclick="getinnerText()" value="innerText" />
</body>
</html>

实例:给元素设置内容

发布了137 篇原创文章 · 获赞 28 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43267344/article/details/104661689