The basic shape
Almost every line of jQuery follows the same pattern:
$(selector).method(arguments);$(selector)selects elements and wraps them in a jQuery object..method(...)acts on them: reads something, changes something, or attaches behaviour.
<h2>Title</h2>
<p class="note">A note.</p>
<p class="note">Another note.</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("h2").text("New title");
$(".note").css("color", "crimson");
</script>New title
A note.
Another note.Implicit iteration
$(".note") selected two paragraphs, and .css() coloured both. You never wrote a loop. jQuery methods that change things apply the change to every selected element. This is called implicit iteration.
If the selection is empty, the method changes nothing and does not complain, as you saw in the previous lesson.
Getters and setters
Many jQuery methods do two jobs, depending on how many arguments you give:
- Getter: called without the value, it reads and returns it.
- Setter: called with a value, it writes it to every selected element.
<p class="item" title="first">Apple</p>
<p class="item" title="second">Banana</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
// Getters
console.log("attr:", $(".item").attr("title"));
console.log("html:", $(".item").html());
console.log("text:", $(".item").text());
// Setter: changes both
$(".item").attr("title", "fruit");
console.log("after:", $(".item").eq(1).attr("title"));
</script>attr: first
html: Apple
text: AppleBanana
after: fruitLook closely at the output:
.attr("title")returnedfirst: getters normally read from the first element only..html()also read only the first..text()is the exception: it joins the text of all selected elements.
When you need a value from every element, loop over them with .each() or .map(), covered later in this section.
Chaining
Every setter returns the same jQuery object it was called on. That means you can call another method straight away:
<p id="msg">Hello</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#msg")
.text("Saved!")
.css("font-weight", "bold")
.addClass("success")
.attr("role", "status");
console.log($("#msg").attr("class"), $("#msg").attr("role"));
</script>success statusOne selection, four changes. Chaining is shorter, and it is faster than selecting #msg four times, because the page is searched only once. Putting each method on its own line, starting with a dot, keeps long chains readable.
A getter returns a plain value (a string, a number), not a jQuery object, so it ends the chain:
<p id="msg">Hello</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#msg").text().hide();
</script>Hello
TypeError: $(...).text(...).hide is not a function.text() with no argument returned the string "Hello", and strings do not have a hide method.
Storing a selection
If you use the same elements several times, keep the jQuery object in a variable. Many developers start such variables with $ as a reminder that they hold a jQuery object:
const $form = $("#signup");
const $email = $form.find("input[type=email]");
$email.addClass("required");
$form.attr("novalidate", "");The $ prefix is only a naming habit; it has no special meaning to JavaScript.
jQuery objects versus DOM elements
A jQuery object wraps plain DOM elements. Sometimes you need the plain element itself, for example to call a browser method jQuery does not wrap:
<input id="name" value="Asha">
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
const $input = $("#name");
const input = $input[0]; // or $input.get(0)
console.log(input.tagName, input.value);
console.log(typeof $input.val, typeof input.val);
</script>INPUT Asha
function undefinedThe plain element has DOM properties such as tagName and value, but no jQuery methods. The jQuery object has jQuery methods. $input[0] unwraps; $(input) wraps again.
Common mistakes
- Expecting a getter to read every element. Only
.text()does; others read the first. - Chaining after a getter, like
.val().addClass(...). - Mixing up the two kinds of object: calling
.hide()on a plain element, or.valueon a jQuery object (use.val()). - Selecting the same element again and again instead of storing it or chaining.
Exercise
Select every paragraph with the class tip, then in one chain: set their text to Read me, make them italic with .css("font-style", "italic"), and add the class seen. Finally, log how many paragraphs were changed.
Show one possible answer
<p class="tip">One</p>
<p class="tip">Two</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
const $tips = $(".tip")
.text("Read me")
.css("font-style", "italic")
.addClass("seen");
console.log($tips.length);
</script>The chain returns the same jQuery object, so $tips still holds both paragraphs.
Key points
- Most jQuery statements have the form $(selector).method(arguments).
- Called with no value, many methods are getters and read from the first element; called with a value, they are setters and change every element.
- Setters return the same jQuery object, so you can chain: $("p").addClass("x").show().
- Getters return a plain value such as a string, which ends the chain.