开发者

JQuery: removing char from a String / selecting

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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜