user1017882
user1017882

Reputation:

How do I select an image element that has a parent of a certain id?

<div id="someId_123">
     <img class"testClass"/>
</div>

Using JQuery, I want to select this image based on its class, and the fact that the div has "123" in its id.

Upvotes: 2

Views: 341

Answers (7)

Steve Valliere
Steve Valliere

Reputation: 1892

You should be able to use '[id*="123"] > .testClass'. The > specifies a parent child relationship.

Upvotes: 2

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102398

$(":div[id*=123] img.testClass");

Here's a working jsFiddle: http://jsfiddle.net/leniel/EdTF8/2/

You also have a typo in your HTML code:

<img class"testClass"/>

should be:

<img class="testClass"/>

I spent some minutes trying to figure out why the jsFiddle wasn't working. It was just because you didn't put a = sign before the class name.

Upvotes: 1

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66971

This will search for 123 anywhere in ID, and grab the image with the class testClass.

$('[id*="123"] img.testClass')

If you want it to be dynamic just do:

$('[id*="' + idNumber + '"] img.' + className)

jsFiddle Demo

Upvotes: 0

Billy Moon
Billy Moon

Reputation: 58531

First grab all images with the class specified (more efficient than selecting all nodes), and then filter for images who's parent has an id matching certain criteria.

$('.testClass').filter(function(){ return this.parent().attr('id').match(/123/) })

Upvotes: 0

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5153

I think this will do:

$("div[id*=123] img.testClass")

Upvotes: 2

Shlomi Komemi
Shlomi Komemi

Reputation: 5545

how about this:

$('img.testClass', '[id*="123"]')

Upvotes: 0

Simon West
Simon West

Reputation: 3788

$("div[id*='123'] img.testClass")

Upvotes: 3

Related Questions