JavaScript:未捕获的TypeError:无法读取prac.js处未定义的属性“ length”:13

时间:2018-09-28 00:42:07

标签: javascript

我试图选择“ contentWrap” div下的所有“ P”子元素,并将所有“ p”元素的颜色更改为红色,但是我继续收到此错误消息。 “未捕获的TypeError:无法读取未定义的属性'length'     在prac.js:13“

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-->

1 个答案:

答案 0 :(得分:0)

您正在尝试根据children(变量getElementsByClassName)的结果访问键wrap。该值不是DOM节点,并且没有children属性,因此ch最终是undefined(因此undefined.length会引发您所看到的错误)。您可能想要获取children返回的元素之一或全部的getElementsByClassName。这是您的操作方式:

第一:

const ch = wrap[0].children;

最后一个:

const ch = wrap[wrap.length - 1].children;

全部(使用类contentWrap遍历每个元素,并对其子元素进行操作):

for(let contentWrap of wrap) {
  const { children } = contentWrap;
}

contentWrap类的第三个(或所需索引)元素:

const ch = wrap[2].children;

您可能想阅读this MDN article on getElementsByClassName