How jQuery id selector can be used to select specific element? Write an example with jQuery
that will hide a paragraph on clicking a button.

This answer is restricted. Please login to view the answer of this question.

Login Now

For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient. When another selector is attached to the id selector, such as h2#pageTitle, jQuery performs an additional check before identifying the element as a match.

Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

Example:

$('#ID')
OR
jQuery('#ID');

Example to hide using jQuery:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>jQuery Hide on click example</title>
</head>
<body>
    <div id="container">
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Vel, libero sapiente. Ad, quam? Inventore impedit magni dolores? Vero expedita hic delectus maiores nisi voluptate, voluptatibus quaerat consequatur, quibusdam dolor id, ea recusandae ducimus ipsum odit dignissimos harum exercitationem doloremque itaque vitae. Excepturi reprehenderit eaque quod voluptatibus magni, deserunt similique veritatis. Labore voluptas voluptatibus enim ut totam non quae cumque obcaecati, omnis fuga nesciunt, esse ab saepe consequuntur doloribus qui. Totam sapiente, voluptate porro, quam optio ratione aliquam doloribus ullam iusto assumenda ipsa distinctio, eum deleniti non reprehenderit consequuntur velit. Dicta eius minima, libero voluptates molestiae ullam nulla autem porro ex!</p>
    </div>

    <button type="button" id="hidecontainer">Hide Container</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
        jQuery(document).ready(function(){
            jQuery("#hidecontainer").on("click", function(){
                jQuery("#container").hide();
            });
        });
    </script>
</body>
</html>
If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .