[javascript] jQuery if Element has an ID?

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.

This question is related to javascript jquery

The answer is


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


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?


Simply use:

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

Pure js approach:

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

JsFiddle Demo


I seemed to have been able to solve it with:

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

Number of .parent a elements that have an id attribute:

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

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

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

You can do this:

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

    /* then do something here */

}

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.


You can do

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