如果我有以下 HTML 结构,我将如何抓取 h2 元素内的强标记之间的文本。
<div class="div1">
<div class="div2>
<h2>
<strong>Default</strong>
<span class="default">(Default)</span>
<a class="remove remove-stage-1" href="#">Remove</a>
<span class="remove remove-stage-2 hidden">
</h2>
目前我正在控制台中尝试并想出了
template = $('.div1')
$(template).find('h2').each(function(index, elem) {
console.log(index + $(this).text(), elem + $(this).text() );
});
这会将我的 elem 输出为
Default (Default) Remove
感谢任何帮助
最佳答案
使用Child Selector (“parent > child”)选择器。
<强> Live Demo
$('.div2 > h2 > strong').text()
描述:选择由“parent”指定的元素的“child”指定的所有直接子元素。
The child combinator (E > F) can be thought of as a more specific form of the descendant combinator (E F) in that it selects only first-level descendants.
关于jquery - 查找包含在 HTML 标签中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21933088/