views:

36

answers:

2

I would like to select only one class from severals with the condition that the selected class has any div-descendant with the id "#exampleId".

I thought something like this could work, but it didn't:

$(".myClass").has(div).attr("id","#exampleId").

The second problem: I have to get rid first of the hash "#". because the String (#exampleId) has been generated dynamically... It looks something like this:

var myString = "#exampleId"  

And the following approach didn't work:

myString.replace('#','');

Thanks in advance

A: 

You could just pass the ID in the selector for has(). No need to remove the # either.

$(".myClass").has("div#exampleId")

Or even do it in one selector:

$(".myClass:has(div#exampleId)")
Matti Virkkunen
Thanks, that solved it !But just for being curious:Would the specific string-replacement work like the method asked above ?
algro
algro: Yes, that would remove all `#` characters. Just remember to store the result somewhere because `replace` doesn't modify the string itself, it returns the modified string.
Matti Virkkunen
+1  A: 

You already accepted an answer, but I'll throw this one out there anyway.

If you have more than a few .myClass elements on the page, it would probably be more efficient to select the #exampleId first, then traverse up to the first .myClass using parents().

$('#exampleId').parents('.myClass:first');

Or if the ID was in a variable, do this:

var myString = "#exampleId";

$(myString).parents('.myClass:first');

These will give you the first parent of the #exampleId that has .myClass.

You could use .closest('.myClass') if you want as well.

patrick dw