<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>
Only to get Trouble Ticket How to write? Thanks
PHP中文网2017-06-26 10:52:49
var val = jQuery(this).find('.js-anviz-body')[0].firstChild.data;
OK!
習慣沉默2017-06-26 10:52:49
First clone the element, then remove the child elements, and finally get the text without child elements
jQuery('.js-anviz-body').clone().children().remove().end().text()
我想大声告诉你2017-06-26 10:52:49
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...
大家讲道理2017-06-26 10:52:49
<html>
<head>
<title></title>
<style type="text/css">
.parent{
width:100px;
height:100px;
}
.child{
width:100px;
height:50px;
}
</style>
</head>
<body>
<p class="parent">
hello world,
<p class="child">welcome!</p>
</p>
<script>
var text = document.querySelector('.parent').firstChild.nodeValue;
console.log(text);
</script>
</body>
</html>
曾经蜡笔没有小新2017-06-26 10:52:49
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']
ringa_lee2017-06-26 10:52:49
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.
大家讲道理2017-06-26 10:52:49
var content = $('.anviz-ellipsis').parent().html().replace(/<[\s\S]*>/g, '');
console.log(content);
打印结果:
// Trouble Ticket
html code:
<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 …
<!-- 混淆代码1 start-->
<p>sdkfjfjfdlkfjsld</p>
<a href="">3w33333</a>
<!-- 混淆代码1 end-->
</p>
<!-- 混淆代码2 start-->
<img src="" alt="">
<a href="">sdfsjflsjdflskdjf</a>
<p>
</p>
<!-- 混淆代码2 end-->
</p>
js code:
<script>
var content = $('.anviz-ellipsis').parent().html().replace(/<[\s\S]*>/g, '');
console.log(content);
</script>