Selectors
A selector is a string that describes which elements you need: by tag, class, id or attribute. The $ function accepts the same selectors as CSS and returns a jQuery object: a set of found elements with methods for working with them.
Finding by selector
<ul id="tasks">
<li class="done">Buy bread</li>
<li>Call Oleg</li>
<li>Write the report</li>
</ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
console.log($('li').length); // 3
console.log($('.done').text()); // Buy bread
console.log($('#tasks li').length); // 3
</script>The length property shows how many elements were found. The text() method returns the element's text.
Kinds of selectors
| Selector | What it finds |
|---|---|
li | All li tags |
.done | Elements with the done class |
#tasks | The element with id="tasks" |
#tasks li | li tags inside #tasks |
input[type="text"] | Inputs with this attribute |
li:not(.done) | Items without the done class |
h1, h2 | All h1 and all h2 |
Any CSS selector works here too.
Acting on all of them at once
A method called on a set applies to every element. No loop needed:
<ul>
<li>Buy bread</li>
<li>Call Oleg</li>
</ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('li').css('color', 'green');
</script>Both items turn green.
Method chaining
Most methods that change something return the same set. So calls can be written one after another:
<h1>My tasks</h1>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('h1').text('To-do list').css('color', 'royalblue');
</script>The heading gets new text and a blue color.
A plain element and a jQuery object
A jQuery object is a wrapper, not the element itself. You get the DOM element by index or with get(), and you wrap a plain element by passing it to $:
<h1>My tasks</h1>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const element = $('h1')[0]; // a plain DOM element
console.log(element.textContent); // My tasks
const wrapped = $(element); // a jQuery object again
console.log(wrapped.text()); // My tasks
</script>Variables holding jQuery objects are often named with a dollar sign: const $list = $('#tasks'). This shows at a glance which methods the variable has.
The same in plain JavaScript
$('li') corresponds to document.querySelectorAll('li'), and $('#tasks') to document.querySelector('#tasks').
Common mistake
Checking whether an element exists like this: if ($('#tasks')). A jQuery object is always created, even an empty one, so the condition is always true. Check the count instead: if ($('#tasks').length > 0).