1

OK so I'm trying to use the contains() selector to modify the css of a div. Please see the fiddle: http://jsfiddle.net/6mdqf/

As you can see, the function selects the parent div even though it doesn't directly contain the text "John"; the text is held in a child div. If you delete the parent div then all works as it should.

How can I ensure only the child div which contains the text "John" is selected whilst the parent div and other children are left alone?

Hope my question makes sense...

code:

<div>
    <div>John Resig</div>
    <div>George Martin</div>
    <div>Malcom John Sinclair</div>
    <div>J. Ohn</div>
</div>

And the js

$("div:contains('John')").css("text-decoration", "underline");
harryg
  • 23,311
  • 45
  • 125
  • 198
  • Please include the code in your question (don't just link to it): http://meta.stackexchange.com/questions/118392/add-stack-overfow-faq-entry-or-similar-for-putting-code-in-the-question – Vidar S. Ramdal Sep 26 '12 at 10:57

4 Answers4

3

As the parent div has children that contains that specific text, your selector selects the parent div and it's children, try the following.

$("div:not(:has(*)):contains('John')").css("text-decoration", "underline");

http://jsfiddle.net/rwQ3u/

Ram
  • 143,282
  • 16
  • 168
  • 197
  • This answer is fantastic, as unlike the accepted answer, it works agnostic of how many levels there are above it. Would be great to get an explanation of how this works. Does has(*) only return elements that have children? – JeopardyTempest Jun 10 '18 at 16:54
  • @JeopardyTempest Thanks. Yes, `has(*)` only return elements that have children and `:not` exclude the selected elements, so divs that have no child elements are selected. textNodes are not returned by `'*'`.. There is `:empty` selector but it only selects elements that have no childNodes. – Ram Jun 10 '18 at 18:36
2

Another way is to call the children elements in the div and use the contains() as a selector in the children.

$("div").children(":contains('John')").css("text-decoration", "underline");​

JSFiddle

QQping
  • 1,370
  • 1
  • 13
  • 26
0

Because you have a div first and It search inside it and find John inside a div and select all, try this:

<div>
    <div class="search">John Resig</div>

    <div class="search">George Martin</div>
    <div class="search">Malcom John Sinclair</div>
    <div class="search">J. Ohn</div>
</div>
​$(document).ready(function(){
    $("div .search:contains('John')").css("text-decoration", "underline");
});
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
0
$("div>:contains('John')").css("text-decoration", "underline");

Edited jsFiddle: http://jsfiddle.net/6mdqf/1/

gabitzish
  • 9,535
  • 7
  • 44
  • 65