DOM - 在任意嵌套的元素之间查找文本 [英] DOM - Find text between arbitrarily nested elements
问题描述
假设我的DOM看起来像这样(纯虚构的例子):
Suppose my DOM looks something like this (purely fictional example):
<div>
<img id="img1" />
Text 1
</div>
<img id="img2" />
<div>
<p>Text 2</p>
<div>
<img id="img3" />
</div>
<img id="img4" />
</div>
我试图做的是在连续元素之间找到所有文本(如果有的话),独立于嵌套级别(所以在这种情况下,我会在#img1
和之间找到
Text1
在#img2
和#img3 ,
/ code>,没有任何/
#img3
和#img4
之间的空字符串)
What I'm attempting to do is to find all text (if any) between consecutive elements independent of nesting level (so in this case, I'd find Text1
between #img1
and #img2
, Text 2
between #img2
and #img3
, and nothing/an empty string between #img3
and #img4
)
我不知道如何将dom结构化。
I don't know ahead of time how the dom is going to be structured.
我试过使用JQuery的< a href =http://api.jquery.com/nextuntil/ =nofollow> nextUntil(),但这似乎只适用于兄弟节点。
I've tried using JQuery's nextUntil(), but that only seems to work for sibling nodes.
推荐答案
我认为我的解决方案更紧密地实现了你指定的内容。这也是使用 contents()
,但也根据ids来进行遍历/过滤。
I think my solution is more closely achieves what you specified. This is also using contents()
but does the traversing/filtering too, based on the ids.
function textBetweenIds(firstId, lastId) {
var texts = [],
betweenIds = false,
recurse = function ($item) {
$item.each(function() {
var text,
$item = $(this),
itemId = $item.attr("id"),
contents = $item.contents();
if (itemId == firstId) {
betweenIds = true;
} else if (itemId == lastId) {
betweenIds = false;
}
if (contents.length == 0 && betweenIds) {
text = $item.text().trim();
if (text != undefined && text.length > 0) {
texts.push(text);
}
}
recurse(contents);
});
return texts;
};
recurse($("body"));
return texts;
}
result = textBetweenIds("img1", "img3");
// result: ["Text 1", "Text 2"]
这篇关于DOM - 在任意嵌套的元素之间查找文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!