If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Review: DOM access with jQuery

To find DOM elements with jQuery, pass a valid CSS selector into the jQuery function:
$("h1"); // selects all the h1s
$("#heading"); // selects the element with id of "heading"
$(".warning"); // selects all the elements with class name of "warning"
Note that the jQuery function can be named $ or jQuery, so those are the same as:
jQuery("h1");  
jQuery("#heading");  
jQuery(".warning");  
Many people prefer $ because it's so short.
The jQuery function will always return a jQuery collection of matching elements, even if there is only one matching element -- or none! You can read more about the jQuery function in their documentation.
Once you've found DOM elements with jQuery, you can do things like set their inner contents with text(): $("#temperature").text("89° Fahrenheit"); (See full example)
You can use the same method text() to get the inner content, by passing it 0 parameters:
var heading = $("#heading").text();
In the next tutorial, you'll learn many more methods to get and set properties of DOM elements.
Behind the scenes, these jQuery functions all use the DOM API that we taught in the HTML/JS course. For example, the $ function uses methods like getElementById() and querySelectorAll(), and attr() uses the getAttribute() method. When you use the $ function, you get to use those functions in fewer lines of code, and also know that your code will work in all of jQuery's supported browsers, which is especially important when using the more recent DOM API functions.

Want to join the conversation?