Reputation: 637
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
Upvotes: 2
Views: 686
Reputation: 322492
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.
Upvotes: 1
Reputation: 65126
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)")
Upvotes: 0