如何选择具有任何ID的元素?例如:
if ($(".parent a").hasId()) {
/* then do something here */
}
I、 我绝对不是jQuery的大师。
像这样:
var $aWithId = $('.parent a[id]');
根据OP的评论,测试如下:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
将返回具有类父级的元素内的所有锚标记,这些元素具有指定的属性ID
您可以使用jQuery的.is()函数。
如果($("parent a").is("#idSelector")){
//Do stuff
}
如果父锚点具有#idSelectorid,则返回true。
您可以进行
document.getElementById(id) or
$(id).length > 0
您可以使用以下代码:
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;
}
});
同样的问题也可以在这里找到:如何检查div是否有id?
具有id
属性的.parent a
元素的数量:
$('.parent a[id]').length
简单方法:
福克斯的例子这是你的html,
<div class='classname' id='your_id_name'>
</div>
Jquery代码:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
我似乎能够用解决它
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
纯js方法:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle演示
简单使用:
$(".parent a[id]");
您可以这样做:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
您可以使用each()函数来评估所有的a标记,并将click绑定到您单击的特定元素。然后用if语句抛出一些逻辑。
看这里的小提琴。
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});