我尝试选择"contentWrap“目录下的所有"P”子元素,并将所有"p“元素的颜色改为红色,但我一直收到此错误消息。“未捕获长度:无法读取在prac.js:13处未定义的属性‘TypeError’”
The JavaScript
const wrap = document.getElementsByClassName("contentWrap");
const p = document.getElementsByTagName("P");
const ch = wrap.children;
const select = (e)=>{
if(e.target.tagName === "P"){
p.style.color = "red";
}
}
for(let i=0; i<ch.length; i++){ //this is line 13 where the error occurs
select(ch[i]);
}
HTML
<div class="contentWrap center">
<div class="newRelease"><image class="br2"src="images/thumbnails/battlefieldps4.png"></image>
<p class="subTitle sline">New Releases</p>
<p class="pContent">Check out the newest releases for each console.</P>
</div>
<div class="preRelease"><image class="br2" src="images/thumbnails/madden.png"></image>
<p class="subTitle sline">Pre Orders</p>
<p class="pContent">Pre order games, for future release dates in advance.</p>
</div>
<div class="news"><image class="br2" src="images/thumbnails/news.png"></image>
<p class="subTitle sline">Gaming News</p>
<p class="pContent">Check out the latest buzz & trending topics for all the different consoles.</p>
</div>
</div> <!--end of contentWrap div-->
发布于 2018-09-28 08:56:13
您正在尝试访问getElementsByClassName
结果上的键children
(变量wrap
)。这个值不是DOM节点,也没有children
属性,因此ch
最终为undefined
(因此undefined.length
抛出您看到的错误)。您可能想要获取getElementsByClassName
返回的一个或所有元素的children
。下面是你如何做到这一点:
首先:
const ch = wrap[0].children;
最后:
const ch = wrap[wrap.length - 1].children;
All (使用类contentWrap
迭代每个元素,并对其子元素执行某些操作):
for(let contentWrap of wrap) {
const { children } = contentWrap;
}
具有类contentWrap
的第三个元素(或所需的任何索引)
const ch = wrap[2].children;
https://stackoverflow.com/questions/52546811
复制相似问题