getElementsByTagName()方法无法按预期工作 [英] getElementsByTagName() method doesnt work as expected

查看:67
本文介绍了getElementsByTagName()方法无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此代码简单地更改所有</p>元素内的文本

I'm trying to simply change the text inside all </p> elements with this code

<html>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<body>
    <p></p>
    <script>
        elem=document.getElementsByTagName("p");
        elem.innerHTML="work";
    </script>
</body>
</html>

据此,我希望work出现在页面上,但结果只是空白页面没有文本.为什么?

from this I expect work to appear on the page, but the result is just a blank page with no text. why?

推荐答案

getElementsByTagName是DOM接口的方法.接受标签 名称作为输入并返回NodeList(某些浏览器选择返回 而是HTMLCollection,这没关系,因为它是的超集 NodeList).

getElementsByTagName is method of the DOM interface. It accepts a tag name as input and returns a NodeList (some browsers chose to return HTMLCollection instead, which is OK, since it is a superset of NodeList).

HTMLCollection,NodeList和对象数组之间的区别

您必须设置HTMLCollection/NodeList的索引.

You have to set the index of your HTMLCollection/NodeList.

elem=document.getElementsByTagName("p");
elem[0].innerHTML="work";

您还可以为HTML文档中的每个p标签执行此操作.

You can also do it for each p tag in your HTML document.

var elem = document.getElementsByTagName("p");

for(var index = 0; index < elem.length; index++){
    elem[index].innerHTML="work";
}

这篇关于getElementsByTagName()方法无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆