user2076675
user2076675

Reputation:

What's the proper way to check if an element has an ID or not with jQuery?

I thought I could check if an element has an ID with has() like this:

if ($button.has('#Menu-Icon')[0] !== undefined) {
   //do stuff
}

but I learned that instead, it checks if there's a descendant which matches the ID. So I don't think this is the right jQuery method to use, but nevertheless it's the only thing that seems to show up when I search the subject on Google.

Which jQuery method is the right one for checking if a given element has a certain ID or not?

Upvotes: 2

Views: 91

Answers (3)

suyesh
suyesh

Reputation: 659

Try something like below which should work:

<div id=""></div> 

 $(document).ready(function(){
       if($('div').attr('id') != ''){
           alert("have id");   
       }else{
            alert("do not have id")   
       }
    });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can check the id property like of the underlying element like

if ($button[0].id == 'Menu-Icon') {
   //do stuff
}

or jQuery way to use .is()

if ($button.is('#Menu-Icon')) {
   //do stuff
}

The has() method is used to filter a set of elements by checking whether those contains elements matching the passed selector, also it returns a jQuery object so checking for undefined will never be true

Upvotes: 4

kapantzak
kapantzak

Reputation: 11750

Check the id using the attr() function like this:

$('button').on('click', function() {
  if ($(this).attr('id') == 'TheID') {
    alert('The button you pressed has the id: "TheID"!');
  } else {
    alert('You pressed a button with another id..');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="TheID">TheID</button>
<button id="anotherID">anotherID</button>

Upvotes: 5

Related Questions