2

I have a script that replaces text and adds a class. It works great, but I have two classes that both have "new" in them and then contain doesn't work. How do I match all the words in the string?

code:

$('body').ready(function(){
    $( "span.conditionHilite:contains('Begagnat')" ).text('Refurbished').addClass("refurbHilite" );
    $( "span.conditionHilite:contains('New Spares')" ).text('New spares').addClass( "refurbHiliteSpares" );
    $( "span.conditionHilite:contains('New')" ).text('New').addClass( "refurbHiliteNew" );
});
EdenSource
  • 3,387
  • 16
  • 29
Xeptor
  • 467
  • 5
  • 18
  • 1
    What about this ? http://stackoverflow.com/questions/15364298/make-jquerys-contains-select-only-exact-string ? – EdenSource Apr 16 '15 at 09:25

3 Answers3

2

To select a span containing an exact text value try this:

$('span').filter(function(){ return $(this).text() == 'New Spares'; }).text('New spares').addClass( "refurbHiliteSpares" );

.filter allows you to apply logic to the elements and return only those that match your test(s) back.

Liza
  • 197
  • 1
  • 15
1

Change contains to has

$(function(){
    $( "span.conditionHilite:has('Begagnat')" ).text('Refurbished').addClass("refurbHilite" );
    $( "span.conditionHilite:has('New Spares')" ).text('New spares').addClass( "refurbHiliteSpares" );
    $( "span.conditionHilite:has('New')" ).text('New').addClass( "refurbHiliteNew" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="conditionHilite">Refurbished</span>  | <br />
<span class="conditionHilite">New spares</span> <br />
<span class="conditionHilite">New</span> <br />
0

Your third line returns the same object as the second line because the selectors you are using contain the same string which is "New". They both match the same element in the DOM.

I would suggest using the jQuery filter method instead. Use .filter() and check the content of the span using the .text() method. If .filter() returns true, add your class, colours etc.

James
  • 442
  • 2
  • 13