jQuery如果Element有ID?

Aar*_*wer 35 javascript jquery

如何选择具有任何ID的元素?例如:

if ($(".parent a").hasId()) {
    /* then do something here */
}
Run Code Online (Sandbox Code Playgroud)

我绝不是jQuery的高手.

A. *_*lff 46

像这样:

var $aWithId = $('.parent a[id]');
Run Code Online (Sandbox Code Playgroud)

根据OP的评论,测试如下:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Run Code Online (Sandbox Code Playgroud)

将返回具有指定属性ID的类parent的元素内的所有锚标记

  • 你的意思是`if($('.parent a [id]').length)`? (4认同)

小智 20

您可以使用jQuery的.is()函数.

if($(".parent a").is("#idSelector")){

//Do stuff
Run Code Online (Sandbox Code Playgroud)

}

如果父锚具有#idSelector id ,它将返回true .

  • 不会。这将告诉您元素是否具有* specific * ID。问题是询问是否有ID。请参阅两年前被接受的答案。 (2认同)
  • 这是一个很好的答案,但是如果您想检查元素是否具有特定的 id!+1 (2认同)

Pie*_*NAY 5

.parent a具有id属性的元素数:

$('.parent a[id]').length
Run Code Online (Sandbox Code Playgroud)


Ani*_*Ani 5

你可以做

document.getElementById(id) or 
$(id).length > 0
Run Code Online (Sandbox Code Playgroud)

  • 不,OP正在尝试确定哪些元素具有使用任何值定义的id属性,而不是通过特定的已知ID进行选择。 (2认同)

bri*_*ang 5

您可以使用以下代码:

   if($(".parent a").attr('id')){

      //do something
   }


   $(".parent a").each(function(i,e){
       if($(e).attr('id')){
          //do something and check
          //if you want to break the each
          //return false;
       }
   });
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到同样的问题:如何检查 div 是否有 id?


Aru*_*ven 5

简单的方法:

Fox 示例,这是您的 html,

<div class='classname' id='your_id_name'>
</div>
Run Code Online (Sandbox Code Playgroud)

查询代码:

if($('.classname').prop('id')=='your_id_name')
{
    //works your_id_name exist (true part)
}
else
{ 
    //works your_id_name not exist (false part)
}
Run Code Online (Sandbox Code Playgroud)