Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect work of jQuery function .text()

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?

like image 824
Dmitry Avatar asked Jan 07 '23 07:01

Dmitry


1 Answers

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)
like image 86
Quentin Avatar answered Jan 17 '23 16:01

Quentin