• jQuery Video Tutorials

jQuery element Selector



The element selector in jQuery is used to select and manipulate HTML elements based on their tag name.

Syntax

Following is the syntax of jQuery element selector −

$("element")

Parameters

The "element" specifies the element that you want to select (e.g., div, p, span).

Example 1

In the following example, we are using the jQuery elememt selector to select all the <p> elements −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function(){
                $('p').css("background-color", "yellow");
            })
        });
    </script>
</head>
<body>
    <p>Paragraph elememt 1.</p>
    <p>Paragraph elememt 2.</p>
    <div>Div element 1.</div>
    <p>Paragraph elememt 3.</p>
    <div>Div element 2.</div>
    <button>Click</button>
</body>
</html>

When we click the button, all the paragraph elememts will be selected and their background color will be changed to yellow.

Example 2

The following example selects the paragraph element and changes the text of that selected paragraph −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("p").text("Text changed!");
            })
        });
    </script>
</head>
<body>
    <p>This is a paragraph.</p>
    <button>Click</button>
</body>
</html>

After clicking the button, the paragraph text will change to "Text changed!".

Example 3

In this example, we are adding a class "highlight" to list items −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("li").addClass("highlight");
            })
        });
    </script>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <button>Click</button>
    </ul>
</body>
</html>

After clicking the button, the all the list items will be highlighted with yellow color background.

jquery_ref_selectors.htm
Advertisements