Select HTML Elements by tag, ID, Class and attribute using jQuery

In this article I will explain how to select elements by tag, ID, Class and attribute using jQuery.

Let’s discuss about jQuery first. jQuery is a JavaScript library written in a way that can minimize steps of JavaScript. That’s simply easy to learn.

“jQuery” denotes the library jQuery. “$” is a variable used to alias “jQuery”. $ is handy to use. But however it’s always recommended to use “jQuery” because the “$” variable might conflict with other JavaScript libraries.

That can be removed using jQuery.noConflict mode.

jQuery selectors are similar to CSS.

To select the elements by a specific tag, use the below


//This will select all the anchor tags
jQuery(‘a’)
//This will select all the p tags
jQuery(‘p’)
//This will select all the h1 tags
jQuery(‘h1’)
Similarly any HTML tag can be used.
To select an element by ID, use the below code
Like the CSS, # must be prepended before the ID attribute to select an element by ID.
//<a href=”#” id=”link1”>Link 1</a>
jQuery(‘#link1’)
//<div id=”div1”>Div 1</div>
jQuery(‘#div’)
Similarly any HTML element identifier can be used.
To select elements by class, use below code
Like the CSS, “.” Must be prepended before the class attribute to select elements by class.
//<a href=”#” class=”links”>Link 1</a>
//<a href=”#” class=”links”>Link 2</a>
jQuery(‘.links’)
//<div class=”div1”>Div 1</div>
jQuery(‘.div1’)

To select elements by attribute, use below code

Let’s understand what an attribute in HTML is first.


//<a class=”link1” name=”aboutus” id=”aboutlink” title=”Click Here” data-caption=”Click Here”>Click Here</a>

In this above example, “a” is an anchor tag. Class, name, id, title and data-caption are the attributes of the anchor tag.

The anchor tag can be selected using an attribute or multiple attributes.

Technically class and ID are attributes but we have specific way to select those by simply prepending “.” Or “#”.


//Select by class
jQuery(‘a[class=”link1”]’)
//Select by name
jQuery(‘a[name=”aboutus”]’)
//Select by ID
jQuery(‘a[id=”aboutlink”]’)
//Select by title
jQuery(‘a[title=”Click Here”]’)
//Select by data attribute
jQuery(‘a[data-caption=”Click Here”]’)
//Select by multiple attributes
jQuery(‘a[class=”link1”][id=”aboutlink”]’)

Hope this helps.

Share this Post