Selecting elements by their tag name

In this post of JQuery, I will explain how to select elements by their tag name.

The syntax is as shown below


$('tagName')

This will return one object or collection of more than one objects based on how many elements are there in the html matching the tagname.

In the below example when the button is pressed, “selectByTagName” javascript method is called and it will in turn call JQuery method as shown below


$('a')

The above JQuery method will select all the elements with tag name ‘a’, which in the below example is 3.

Below is the complete code


<html>
    <head>
        https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
    </head>
    <body>
        
            function selectByTagName() {
                var $element = $('a');
                alert($element.length);
            }
        
        <input id="button" name="button" type="button" value="button" onclick="selectByTagName();"/>
        <br>
        <a class="class1">www.google.com</a>
        <br>
        <a class="class2">www.rediff.com</a>
        <br>
        <a class="class1 class3">www.yahoo.com</a>
    </body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s