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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)")

2 Comments

Thanks, that solved it ! But just for being curious: Would the specific string-replacement work like the method asked above ?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.