gpt4 book ai didi

javascript - 在另一个元素之后查找具有特定类/标签名称的第一个元素

转载 作者:行者123 更新时间:2023-11-30 11:51:30 24 4
gpt4 key购买 nike

我有一个如下所示的网页:

<h1 id="a">A</h1>
contents
<p class="paragraph">stuff</p>
more contents

<h1 id="b">B</h1>
contents
<p class="paragraph">stuff I need</p>
more contents

<h1 id="c">C</h1>
contents
<p class="paragraph">stuff</p>
more contents

et cetera

如何选择 <p class="paragraph">标题后的标签 id="b" (内容是“我需要的东西”)?

我想过定位<h1 id="b">B</h1>的索引在$("h1")然后在 $("p.paragraph") 中访问该索引,但这在我的具体情况下不起作用。

编辑:一个更好的例子:https://jsfiddle.net/n7zstmw8/

最佳答案

选择是:

$('#b + .paragraph')

Next Adjacent Selector (“prev + next”): Selects all next elements matching "next" that are immediately preceded by a sibling "prev".

片段:

$(function () {
console.log($('#b + .paragraph').text());
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<h1 id="a">A</h1>
contents
<p class="paragraph">stuff</p>
more contents

<h1 id="b">B</h1>
contents
<p class="paragraph">stuff I need</p>
more contents

<h1 id="c">C</h1>
contents
<p class="paragraph">stuff</p>
more contents

如果下一个元素不相邻你可以使用 nextAll:

$(function () {
console.log($('#b').nextAll('.paragraph:first').text());
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<h1 id="a">A</h1>
<span class="inbetween">In between stuff</span>
<p class="paragraph">stuff</p>
<span class="inbetween">In between stuff</span>

<h1 id="b">B</h1>
<span class="inbetween">In between stuff</span>
<div class="moreinbetween">
More stuff
</div>
<p class="paragraph">stuff I need</p>
<span class="inbetween">In between stuff</span>

<h1 id="c">C</h1>
<span class="inbetween">In between stuff</span>
<p class="paragraph">stuff</p>
<span class="inbetween">In between stuff</span>

关于javascript - 在另一个元素之后查找具有特定类/标签名称的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39310922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com