-->

20 April 2021

To select page elements by ID in jQuery

  Asp.Net CS By Example       20 April 2021
To select page elements by ID in jQuery

 In this post we are exploring more about To select page elements by ID in jQuery. jQuery specializes in letting we pick out page elements so we can work on them. In this example, we will see how to pick out a particular <p> element based on its ID attribute value.

 When we use jQuery, we usually use a function named jquery( ) to gain access to the jQuery library. In fact, there is a shortcut: we can also call the function $( ), and that is what we will do.

 To access an element with the ID "id", call the function $(#id), which returns a set of all elements with that ID. Because IDs must be unique, that is only one element. To verify that we have selected a particular <p> element, we will turn its background cyan when the user clicks a button with the jQuery toggleClass( ) function.

jqscript2.1.html
<html>
<head>
    <title>Select a paragraph</title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        function stripe() {
            $('#third')
            .toggleClass('striped');
        }
    </script>
    <style>
        p.striped {
            background-color: cyan;
            width: 300px;
        }
    </style>
</head>
<body>
    <h1>Select a paragraph</h1>
    <div>
        <p>This is paragraph 1.</p>
        <p>This is paragraph 2.</p>
        <p id="third">
         This is paragraph 3.
        </p>
        <p>This is paragraph 4.</p>
    </div>
    <form>
        <input type="button"
               value="Stripe"
               onclick="stripe()"
        </input>
    </form>
</body>
</html>


Output:

logoblog

Thanks for reading To select page elements by ID in jQuery

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.