Reputation: 3667
How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Upvotes: 57
Views: 178546
Reputation: 21
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
Upvotes: 2
Reputation: 83
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Upvotes: 4
Reputation: 119
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});
Upvotes: 0
Reputation: 1959
Simple way:
Fox example this is your 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)
}
Upvotes: 5
Reputation: 856
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
Upvotes: 3
Reputation: 792
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
Upvotes: 52
Reputation: 74420
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
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
Upvotes: 66
Reputation: 46178
Number of .parent a
elements that have an id
attribute:
$('.parent a[id]').length
Upvotes: 5
Reputation: 421
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?
Upvotes: 7