Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

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>
like image 64
kapantzak Avatar answered Dec 20 '25 17:12

kapantzak


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

like image 24
Arun P Johny Avatar answered Dec 20 '25 19:12

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!