user1040259
user1040259

Reputation: 6509

JQuery select based on more than one variable (specific string)

I want to create a couple if statements grabbing the ID using contains (*=) and img that equals (=). What might I be doing wrong?

if($("div[id*='Point_'], [img='gray.png']").length > 0 ) {

// do something gray
}

if($("div[id*='Point_'], [img='red.png']").length > 0 ) {

// do something red
}
<div id="Point_1">
    <img src="gray.png">
</div>
<div id="Point_2">
    <img src="red.png">
</div>

Upvotes: 1

Views: 324

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

You're attempting to use a tag selector like an attribute selector. If you want to match the <img> tag where the src attribute equals gray.png then the correct selector is $('img[src="gray.png"]').

Also, this may or may not be correct for what you want to do, but the comma in a jQuery selector acts like an OR, so you're saying "Give me any <div> element where the id attribute contains the text 'Point_' OR any <img> element where the src matches 'gray.png'." If that's what you want, then ok.

However, it seems more likely that what you want to do is select the <img> element with a src equal to gray.png that is within a <div> with an ID containing 'Point_', so the selector should be:

$('div[id*="Point_"] img[src="gray.png"]')

Upvotes: 4

Craine
Craine

Reputation: 490

If you are trying to select the specific string you need to drop the comma from your string. Separating the selectors with a comma selects multiple elements based on any selector. No comma selects matching on all selectors. See here.

Upvotes: 2

Related Questions