I'm trying to get all the text from HTML without any tags by using $('.container').text()
. Instead of getting clear text I get text with duplicate parts.
Here is my HTML code:
<div class="v highlighted" id="4">
<span class="vn" id="4">4</span>
<span class="p">Text-0</span><br>
<span class="p">
<span class="wj">
Text-1
<span class="w">Text-2</span>
Text-3
</span>
</span><br>
</div>
<script>
console.log($(".highlighted :not(.vn)").text());
</script>
In the console I see this result:
Text-0Text-1Text-2Text-3Text-1Text-2Text-3Text-2
Does anybody know why it happens?
Look at what .highlighted :not(.vn)
matches.
It matches:
<span class="p">Text-0</span>
<br>
<span class="p"><span class="wj">Text-1<span class="w">Text-2</span>Text-3</span></span>
<span class="wj">Text-1<span class="w">Text-2</span>Text-3</span>
<span class="w">Text-2</span>
<br>
Since you have some text contained in a span which is contained in another span and both those spans match the selector, you get the content of the outer span and the (identical) content of the inner span.
You probably want to use a child combinator (>
) instead of a descendant combinator () in your selector.
.highlighted > :not(.vn)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With