I have answered a similar question before. When traversing nodeChild, this text is an instance of Text(). You can refer to the question I answered before: /q/10...
To understand the question, you probably want to get all the text that belongs to the parent element but not the child element
Assuming you know the text position, it's simpler, if the text is at the beginning:
//pp = """<p class="mui-media-body js-media-body js-anviz-body">Trouble Ticket
<p class="anviz-ellipsis js-des">You can sumbit your trouble and …</p>
</p>"""
var childNodes = pp.childNodes;
var text = childNodes[0]; // Trouble Ticket
If the text position is uncertain, or even there are multiple, it is necessary to traverse the child elements of the parent element at this time and find all elements whose node attributes are text:
//pp = """<p class="mui-media-body js-media-body js-anviz-body">
Trouble Ticket
<p class="anviz-ellipsis js-des">You can sumbit your trouble and …</p>
Trouble Ticket2
</p>"""
var childNodes = pp.childNodes;
var textNodes = [];
childNodes.forEach(function(node){
if (node.nodeType === 3) {
textNodes.push(node);
} // 3 为 文本
});
//textNodes === ['Trouble Ticket', 'Trouble Ticket2']
The clone method above is better. What if there is text behind the p tag? Using firstChild only gets the first text node, and it needs to be traversed to get the subsequent text nodes.
It’s best to add a label to wrap it up for easy access
OK!
First clone the element, then remove the child elements, and finally get the text without child elements
I have answered a similar question before. When traversing nodeChild, this text is an instance of
Text()
. You can refer to the question I answered before: /q/10...It is more reasonable to add a span to cover it
To understand the question, you probably want to get all the text that belongs to the parent element but not the child element
Assuming you know the text position, it's simpler, if the text is at the beginning:
If the text position is uncertain, or even there are multiple, it is necessary to traverse the child elements of the parent element at this time and find all elements whose node attributes are text:
The clone method above is better. What if there is text behind the p tag?
Using firstChild only gets the first text node, and it needs to be traversed to get the subsequent text nodes.
html code:
js code: