Jquery "contains" multiple values
Asked Answered
F

5

8

I am finding all the divs in a document which contains inside a text: 'thetext' and i am changing this text:

$("div:contains('thetext'):not(:has(*))").each(function () {

  $(this).text($(this).text() + " anotherTextAddedBefore");

 })

Is it possible to put inside contains multiple values? I would like to find the divs whic contains: 'thetext', but also another values, for example: 'thetext1', 'thetext2',etc

I`d want to make it in one procedure and not in more: dont want to use as many procedures as texts i´d like to find.

Thanks!

Findlay answered 23/4, 2014 at 15:25 Comment(5)
$("div:contains('thetext'), div:contains('thetext1'), div:contains('thetext2')") is possibleChutzpah
$("div:contains('thetext'):contains('thetext1'):contains('thetext2')")Scission
Wouldn't that be an AND condition @A.Wolff?Leathern
@JayBlanchard Ya but that's how i understand question, i can be wrong I would like to find the divs whic contains: 'thetext', but also another values, for example: 'thetext1', 'thetext2',etcScission
Ah, on re-reading I see what you're saying @A.WolffLeathern
S
14

You can use the multiple selector as a or condition like

$("div:not(:has(*))").filter(":contains('thetext'), :contains('thetext2')").each(..)
Schwarzwald answered 23/4, 2014 at 15:29 Comment(0)
L
15

A selector like this provides an OR condition -

$("div:contains('thetext'), div:contains('thetext1'), div:contains('thetext2')")

A selector like this provides an AND condition -

$("div:contains('thetext'):contains('thetext1'):contains('thetext2')")

Demo - http://jsfiddle.net/jayblanchard/3a72h/

Leathern answered 23/4, 2014 at 15:29 Comment(0)
S
14

You can use the multiple selector as a or condition like

$("div:not(:has(*))").filter(":contains('thetext'), :contains('thetext2')").each(..)
Schwarzwald answered 23/4, 2014 at 15:29 Comment(0)
H
4

You can have an array

var array = ['John', 'Martin'];


$(array).each(function () {

    $("div:contains(" + this + ")").css("text-decoration", "underline");

});

WORKING EXAMPLE

Halfon answered 23/4, 2014 at 15:32 Comment(1)
Thanks Underscore! It is short, simple and works nicely!Bop
T
2

Just adding one more point to above answers, if you want to select elements that dont have particular values then you can use

$("div:not(:contains('thetext'), :contains('thetext1'),:contains('thetext2'))")

works as and condition

Towage answered 21/5, 2017 at 16:43 Comment(0)
H
1

You can create an array and loop it:

var containsVals = ["text1","text2"];

for(var i=0;i<containsVals.length;i++){
    $("div:contains("+ containsVals[i] +"):not(:has(*))").each(function () {
      $(this).text($(this).text() + " anotherTextAddedBefore");
    });
}
Hartman answered 23/4, 2014 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.