我认为没有一种真正简单的方法来获取所有节点并将它们分开等,但这确实是可能的。由于我不知道您打算如何处理文本,因此我制作了一个整洁的小对象,其中包含应该更容易使用的所有内容,或者您可以更改代码以满足您的需求:
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 http://jsfiddle.net/3h5Vn/
这将返回:
{"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"},
}
您可以根据行号(从零开始)、标记名、文本内容或您需要的任何其他内容来过滤此内容?