如何在给定类名的特定div中找到dom子节点?

我有一个分层div部分如下:


<div class="class1">

    <div class="class2">

        <button class="class3" onclick="bclick(this)">b1</button>

    </div>

    <div class="class4">

        <p>first text</p>

    </div>

</div>

<div class="class1">

    <div class="class2">

        <button class="class3" onclick="bclick(this)">b2</button>

    </div>

    <div class="class4">

        <p>second text</p>

    </div>

</div>

<div class="class1">

    <div class="class2">

        <button class="class3" onclick="bclick(this)">b3</button>

    </div>

    <div class="class4">

        <p>third text</p>

    </div>

</div>

<div class="class1">

    <div class="class2">

        <button class="class3" onclick="bclick(this)">b4</button>

    </div>

    <div class="class4">

        <p>fourth text</p>

    </div>

</div>

当我点击任何按钮,说按钮b3,我想third text在javascript中获取文本,而不是jquery。


所以在我的bclick()函数中,我将按如下方式访问根元素:


function bclick(obj) {

    let class1obj = obj.parentNode.parentNode;

    // don't know what to do next to get to class 4 and then get the <p> text. Please help.

}

我想进入class4获取<p>标签的内容,在这种情况下b3我想要的文本third text。


请帮忙。不知道该怎么做。请注意,因为多次出现一个类,我想只获得一个包含单击按钮的特定类。


婷婷同学_
浏览 857回答 2
2回答

慕的地10843

您可以Element.querySelector()在父级上使用并为每个父元素选择<p>内部.class4元素。obj.parentNode.parentNode.querySelector('.class4&nbsp;p')请参阅工作代码段

达令说

您可以Document.querySelector()在父节点上使用:Document方法querySelector()返回文档中与指定选择器或选择器组匹配的第一个Element。如果未找到匹配项,则返回null。function bclick(obj) {&nbsp; let class1obj = obj.parentNode.parentNode.querySelector('.class4 > p');&nbsp; console.log(class1obj.textContent);}<div class="class1">&nbsp; &nbsp; <div class="class2">&nbsp; &nbsp; &nbsp; &nbsp; <button class="class3" onclick="bclick(this)">b1</button>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="class4">&nbsp; &nbsp; &nbsp; &nbsp; <p>first text</p>&nbsp; &nbsp; </div></div><div class="class1">&nbsp; &nbsp; <div class="class2">&nbsp; &nbsp; &nbsp; &nbsp; <button class="class3" onclick="bclick(this)">b2</button>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="class4">&nbsp; &nbsp; &nbsp; &nbsp; <p>second text</p>&nbsp; &nbsp; </div></div><div class="class1">&nbsp; &nbsp; <div class="class2">&nbsp; &nbsp; &nbsp; &nbsp; <button class="class3" onclick="bclick(this)">b3</button>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="class4">&nbsp; &nbsp; &nbsp; &nbsp; <p>third text</p>&nbsp; &nbsp; </div></div><div class="class1">&nbsp; &nbsp; <div class="class2">&nbsp; &nbsp; &nbsp; &nbsp; <button class="class3" onclick="bclick(this)">b4</button>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="class4">&nbsp; &nbsp; &nbsp; &nbsp; <p>fourth text</p>&nbsp; &nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript