Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 901
Aaron Brewer Avatar asked Jun 24 '13 14:06

Aaron Brewer


People also ask

How do you check if an element has a specific ID?

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.

How do you find if element with specific ID exists or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do you check if an element has an attribute in jQuery?

Using jQuery The idea is to use the . attr() method, which returns the attribute's value for an element if it is present and returns undefined if the attribute doesn't exist.


2 Answers

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

like image 162
A. Wolff Avatar answered Sep 25 '22 10:09

A. Wolff


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.

like image 26
viren Kalkhudiya Avatar answered Sep 23 '22 10:09

viren Kalkhudiya