javascript - 使用 javascript/jquery 选择仅跟随某些元素的文本

标签 javascript jquery html web-scraping

如以下代码片段所示,我有多个文本 div,其中有一个粗体部分,然后是一个换行符,然后是一段文本。我可以 find() 粗体部分,但是如何使用 javascript/jquery 仅获取粗体部分后换行符后面的文本部分?

<div class="thecontent">
any amount of text or html elements before
<b>
    the bolded text
</b>
<br>
the text I need together with the bolded text which can contain other html
elements apart from line breaks and bolded blocks
<br>
<b>
    posibility of more bolded and text couples further in the div
</b>
<br>
and some more text to go with the bolded text
</div>

单个 div 中可以有多个粗体部分和文本对,所需的文本片段可以以换行符、另一个粗体部分或 div 的结尾结束。可能还有其他 html 元素,如 <a href>在文本 block 中。

我可以得到 <b> </b> 的内容与 .find('b')我试过使用 nodeType == 3选择文本节点,但这只会让我获得所有文本。

很遗憾,我无法更改页面的 html。有人有解决办法吗?提前致谢:)

根据要求,输入将以粗体显示,以阻止换行符及其后的文本。我需要在换行符或另一个粗体部分之前的文本。

输出将是一个变量中的粗体文本和换行符之后但直到下一个换行符或另一个变量中的粗体元素的文本。

所以 html 示例的输出是:the bolded text + the text I need together with the bolded text which can contain other html elements apart from line breaks and bolded blocks

posibility of more bolded and text couples further in the div + and some more text to go with the bolded text

最佳答案

我不认为有一种非常简单的方法来获取所有节点并将它们分开等,但它肯定是可能的。由于我不知道你打算用文本做什么,我制作了一个简洁的小对象,其中包含应该更容易使用的所有内容,或者你可以更改代码以满足你的需要:

var elem    = $('.thecontent').get(0).childNodes,
    content = {},
    i = 0;

for (key in elem) {
    var type = elem[key].tagName ? elem[key].tagName : 'text';
    content[i] = {};
    content[i][type] = elem[key].tagName == 'B' ? $(elem[key]).text() : elem[key].nodeValue;
    i++;
}

console.log( content );

FIDDLE

返回:

{"0": {"text" : "any amount of text or html elements before"},
 "1": {"B"    : "the bolded text"},
 "2": {"text" : "\n"}, //also returns newlines
 "3": {"BR"   : null},
 "4": {"text" : "the text I need together with the bolded text which can contain other html elements apart from line breaks and bolded blocks"},
 "5": {"BR"   : null},
 "6": {"text" : "\n"},
 "7": {"B"    : " posibility of more bolded and text couples further in the div"},
 "8": {"text" : "\n"},
 "9": {"BR"   : null},
 "10":{"text" : "and some more text to go with the bolded text"},
}

您可以根据行号(从零开始)、标记名、文本内容或您需要的任何其他内容进行过滤?

关于javascript - 使用 javascript/jquery 选择仅跟随某些元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14894691/

相关文章:

javascript - on Change 事件仅触发一次

jquery - 无法操纵轮播指示器的右边距/位置

javascript - 我需要从网站中选择一个元素 "x",但该网站加载元素“x”太慢

javascript - 将字符串转换为函数

javascript - 两个区域的垂直可拖动划分

javascript - 如何在网站上线时连续弹起物体

jquery - rails : returning a controller object to AJAX caller

javascript - 根据验证结果切换元素可见性

javascript - 如何协调 Javascript 与柯里化(Currying)和函数组合

javascript - 使用javascript向按钮添加事件