In jQuery how to select an element by its ID

I'm learning jQuery and trying to understand how to select HTML elements by their ID. I want to apply some changes (like hiding or styling) to a specific element on my page, but I'm not sure what the correct jQuery syntax is.

  <div id="myDiv">Hello World</div>

What is the correct way to select this div using jQuery so that I can manipulate it? Also, are there any common mistakes to avoid when selecting elements by ID?

1 Answer

In jQuery, you use the dollar sign $ followed by parentheses. Inside the parentheses, you pass a CSS-style selector as a string.

To select an element by ID, use a # before the ID name, just like in CSS. 

 $('#myDiv')

use like

 $('#hideBtn').click(function() {
    
  });

We use cookies to enhance your experience, to provide social media features and to analyse our traffic. By continuing to browse, you agree to our Privacy Policy.