jQuery · The DOM

DOM Manipulation

Most jQuery code reads or changes something on the page: a heading’s text, an input’s value, a link’s href. One rule makes it easy: call a method with no value to read, with a value to write.

Beginner 5 min Lesson 5 of 22 Runnable examplesExamples use jQuery 3.x.
Before you start:Selectors
0/22 in jQuery
On this page · 5 min · Beginner

Learning objectives#

  • Read and set text, HTML and input values
  • Use .attr() vs .prop() correctly
  • Store and read data-* values with .data()
  • Avoid XSS by preferring .text() for user input

Explanation#

.text() reads/sets plain text; .html() reads/sets HTML markup; .val() reads/sets form field values.

Getter vs setter: $("#title").text() returns the text of the first match; $("#title").text("Hi") sets it on every match and returns the jQuery object for chaining.

.attr("href") works with HTML attributes as written; .prop("checked") / .prop("disabled") work with live DOM properties. Use .prop for checked, selected and disabled.

.data("price") reads data-price="499" and converts it to a number; .data("x", value) stores values in jQuery’s cache (it does not change the HTML attribute).

Never put user input into .html(): a name like <img src=x onerror=alert(1)> would run. Use .text(), which escapes it.

Syntax#

JavaScript Illustrative
$('#title').text();             // read
$('#title').text('New title');  // write
$('#email').val('a@b.com');
$('#link').attr('href', '/home');
$('#agree').prop('checked', true);
$('#card').data('price');       // data-price="499" → 499

Code example: Reading and writing a product card#

HTMLReading and writing a product card Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<div id="card" data-price="499" data-stock="3" style="font-family:sans-serif">
  <h3 class="name">Notebook</h3>
  <a class="more" href="/products/1">Details</a>
  <label><input type="checkbox" class="gift"> Gift wrap</label>
  <input class="qty" value="1" size="3">
  <p class="note"></p>
</div>
<script>
  $(function () {
    const $card = $('#card');
    console.log('Name:', $card.find('.name').text());
    console.log('Price:', $card.data('price'), typeof $card.data('price'));
    console.log('Link:', $card.find('.more').attr('href'));


    $card.find('.name').text('Spiral Notebook');
    $card.find('.qty').val(2);
    $card.find('.gift').prop('checked', true);
    console.log('Gift?', $card.find('.gift').prop('checked'));


    const userInput = '<b>Asha</b>';
    $card.find('.note').text('Ordered by ' + userInput);   // shown as plain text, not bold
  });
</script>
Expected output
Name: Notebook
Price: 499 number
Link: /products/1
Gift? true
(The heading becomes “Spiral Notebook”, quantity shows 2, the checkbox is ticked, and the note shows the literal text “Ordered by <b>Asha</b>”.)
Opens this example in the full playground

Step-by-step explanation#

  1. .text() with no argument reads the heading.
  2. .data("price") converts "499" to the number 499.
  3. .attr("href") reads the attribute exactly as written.
  4. Setters (.text("..."), .val(2), .prop("checked", true)) update the page.
  5. .text() escapes the user input, so the <b> tag is shown, not executed.

Real-world use case#

A shopping cart reads data-price and data-stock from each product card, updates quantity inputs with .val(), and shows totals with .text().

Common mistakes#

.attr("checked") for checkbox state

The attribute shows the initial state, not the current one. Use .prop("checked").

.html() with user data

Inserting untrusted text as HTML enables XSS. Use .text().

Expecting .data() to update the attribute

.data("x", 1) stores in memory; data-x in the HTML is unchanged. Use .attr("data-x", 1) if CSS selectors need it.

Best practices#

  • .text() for user content
  • .prop() for checked/disabled/selected
  • data-* attributes for values the script needs
  • Chain setters on one selection

Remember this#

No argument = get. With argument = set.

attr = what the HTML says. prop = what the element is now.

User input → .text(), never .html().

Practice exercise#

Your task: An input #price and a button #apply: on click, read the price, add 18% GST, and show it in #total formatted to 2 decimals.

Need a hint?
parseFloat($("#price").val()) * 1.18, then .toFixed(2).
Show solution
HTML Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<input id="price" value="100"> <button id="apply">Add GST</button>
<p>Total: <span id="total">–</span></p>
<script>
  $(function () {
    $('#apply').on('click', function () {
      const price = parseFloat($('#price').val()) || 0;
      $('#total').text((price * 1.18).toFixed(2));   // 118.00
    });
  });
</script>
Opens this example in the full playground

Mini quiz#

DOM Manipulation quizMultiple choice Question 1 of 3

Which call reads the current value of an input?

Score so far: 0/0

Want more? Practise all jQuery MCQs · jQuery interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.