jQuery 如果 Element 有 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17277821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:44:35  来源:igfitidea点击:

jQuery if Element has an ID?

javascriptjquery

提问by Aaron Brewer

How would I select elements that have any ID? For example:

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

if ($(".parent a").hasId()) {
    /* then do something here */
}

I, by no means, am a master at jQuery.

我绝不是 jQuery 的高手。

回答by A. Wolff

Like this:

像这样:

var $aWithId = $('.parent a[id]');

Following OP's comment, test it like this:

按照 OP 的评论,像这样测试:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)

Will return all anchor tags inside elements with class parent which have an attribute ID specified

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

回答by viren Kalkhudiya

You can use jQuery's .is() function.

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

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

//Do stuff

}

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

//Do stuff

}

It will return true if the parent anchor has #idSelectorid.

如果父锚具有#idSelectorid ,它将返回true 。

回答by Pierre de LESPINAY

Number of .parent aelements that have an idattribute:

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

$('.parent a[id]').length

回答by Ani

You can do

你可以做

document.getElementById(id) or 
$(id).length > 0

回答by ArunValaven

Simple way:

简单的方法:

Fox example this is your html,

Fox 示例,这是您的 html,

<div class='classname' id='your_id_name'>
</div>

Jquery code:

查询代码:

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

回答by brian_wang

You can using the following code:

您可以使用以下代码:

   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;
       }
   });

The same question is you can find here: how to check if div has id or not?

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

回答by Wallstrider

Pure js approach:

纯js方法:

var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));

JsFiddle Demo

JsFiddle 演示

回答by Broxzier

Simply use:

只需使用:

$(".parent a[id]");

回答by justMoritz

I seemed to have been able to solve it with:

我似乎已经能够解决它:

if( $('your-selector-here').attr('id') === undefined){
    console.log( 'has no ID' )
}

回答by Ian Dev

You can do this:

你可以这样做:

if ($(".parent a[Id]").length > 0) {

    /* then do something here */

}