Aaron Brewer
Aaron Brewer

Reputation: 3667

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.

Upvotes: 57

Views: 178546

Answers (11)

Ian Dev
Ian Dev

Reputation: 21

You can do this:

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

    /* then do something here */

}

Upvotes: 2

justMoritz
justMoritz

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

TGEE
TGEE

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

ArunValaven
ArunValaven

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

Wallstrider
Wallstrider

Reputation: 856

Pure js approach:

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

JsFiddle Demo

Upvotes: 3

viren Kalkhudiya
viren Kalkhudiya

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

A. Wolff
A. Wolff

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

Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46178

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

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

Upvotes: 5

brian_wang
brian_wang

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

Broxzier
Broxzier

Reputation: 2949

Simply use:

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

Upvotes: 1

Ani
Ani

Reputation: 4523

You can do

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

Upvotes: 7

Related Questions