Lesson 4 of 12

jQuery Get and Set Content

Once you have selected an element, you usually want to read something from it or change it: the text of a heading, the value someone typed, the src of an image. To get and set content, jQuery uses one simple pattern for all of these. Call a method without a value to get; call it with a value to set. The plain JavaScript versions are covered in DOM Manipulation.

The getter and setter pattern

MethodGets / setsPlain JavaScript
.text()The text content, with tags ignoredtextContent
.html()The HTML markup inside the elementinnerHTML
.val()The current value of an input, select or textareavalue
.attr(name)An HTML attribute, such as href or altgetAttribute() / setAttribute()
.prop(name)A live DOM property, such as checked or disabledthe property itself, e.g. el.checked
.data(key)Values from data-* attributes, plus your own stored datadataset

There is one rule to remember when you get and set content. A getter reads from the first matched element only (except .text(), which joins the text of all of them). A setter changes every matched element. So $('.price').val() gives you one value, while $('.price').val('0') sets them all.

Get and set content: text, HTML and form values

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Live profile card with .val() and .text()</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
    .card { max-width: 260px; margin-top: 12px; padding: 12px; border: 1px solid #ccc; border-radius: 8px; }
    .card h2 { margin: 0 0 4px; font-size: 1.2rem; }
    label { display: block; margin-top: 8px; }
  </style>
</head>
<body>
  <label for="name">Name</label>
  <input id="name" type="text" value="Meena Raj">
  <label for="role">Role</label>
  <select id="role">
    <option>UI designer</option>
    <option selected>Front-end developer</option>
    <option>Content writer</option>
  </select>

  <div class="card">
    <h2 id="card-name"></h2>
    <p id="card-role"></p>
  </div>

  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <script>
function updateCard() {
  $('#card-name').text($('#name').val() || 'Your name');
  $('#card-role').text($('#role').val());
}

$('#name, #role').on('input change', updateCard);
updateCard();   // fill the card on load
  </script>
</body>
</html>

.val() on a <select> returns the value of the selected option (or its text if it has no value attribute). On a <select multiple> it returns an array.

.text() or .html()? Think about safety

.text('…') treats the string as plain text: any < characters are shown literally. .html('…') parses the string as HTML and builds real elements. Use .html() only with markup you wrote. Never pass something a user typed, or data from a server you do not control, to .html() – an attacker could inject a script or an image with an onerror handler. This attack is called cross-site scripting (XSS).

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>.text() versus .html() with the same string</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
    .box { padding: 8px; margin: 6px 0; border: 1px dashed #999; }
  </style>
</head>
<body>
  <p>Input: <code>Price: <strong>₹499</strong></code></p>
  <p>With .text():</p>
  <div id="as-text" class="box"></div>
  <p>With .html():</p>
  <div id="as-html" class="box"></div>

  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <script>
const input = 'Price: <strong>₹499</strong>';

$('#as-text').text(input);   // shows the tags as characters – always safe
$('#as-html').html(input);   // builds a real <strong> – only for trusted markup
  </script>
</body>
</html>

Watch out: A common bug is reading .html() when you meant the plain words. If a heading contains an icon or a <span>, .html() returns the tags too. Use .text() to read what a person actually sees.

Setting values with a function

Every setter also accepts a function instead of a fixed value. jQuery calls it once for each matched element, passing the element’s index and its current value, and uses whatever you return. This is handy when each element needs a slightly different result based on what it already contains – for example, adding a prefix to every price, or numbering a list of steps:

// Before: <li class="step">Boil water</li> <li class="step">Add tea powder</li> …
$('.step').text((index, oldText) => `Step ${index + 1}: ${oldText}`);

// Add a currency sign to every price cell that doesn't have one yet
$('.price').text((index, oldText) => oldText.startsWith('₹') ? oldText : '₹' + oldText);

Setters return the jQuery object, so you can keep chaining (see jQuery Introduction): $('#title').text('Menu').attr('title', 'Lunch menu'). Getters return a value (a string, number or boolean), so a chain always ends at a getter.

Attributes vs properties: .attr() and .prop()

An attribute is what you wrote in the HTML. A property is the live value on the DOM object. For most things – href, src, alt, id – they match, and .attr() is fine. For states that change while the page is open, such as checked, selected and disabled, use .prop(). When someone ticks a checkbox, the checked attribute in the HTML does not change; only the property does. So .prop('checked') returns true or false reliably.

To remove an attribute entirely, use .removeAttr('title'). To set several at once, pass an object: .attr({ src: 'thali.jpg', alt: 'South Indian thali' }).

Reading data-* attributes with .data()

HTML lets you store your own information in data-* attributes, such as data-price="70". jQuery’s .data('price') reads it and converts it for you: "70" becomes the number 70, "true" becomes true, and JSON in the attribute becomes an object. Hyphenated names are read in camelCase, so data-max-qty is .data('maxQty').

// <button id="add" data-price="70" data-max-qty="5">Add dosa</button>
const price  = $('#add').data('price');    // 70 (a number)
const maxQty = $('#add').data('maxQty');   // 5

// Setting with .data() stores the value in memory only…
$('#add').data('price', 80);
$('#add').attr('data-price');              // still "70" in the HTML

// …so use .attr() if CSS or other code reads the attribute
$('#add').attr('data-price', '80');

Tip: Because .data(key, value) does not write to the HTML attribute, CSS selectors like [data-state="open"] will not notice the change. Use .attr('data-state', 'open') when the attribute itself must change.

Further reading

Key takeaways

  • Call a method without a value to get, with a value to set.
  • Getters read the first matched element; setters change all of them.
  • .text() is safe for any string; .html() parses markup and must only get trusted HTML.
  • Use .val() for form fields and .prop() for live states like checked and disabled.
  • .data() reads data-* attributes with type conversion but does not write back to the HTML.

Quick quiz

Check what you learned – pick an answer.

1. A user types their name into a comment box. Which line safely shows it on the page?

2. How do you find out whether a checkbox is currently ticked?

3. An element has data-max-qty="5". What does $(el).data('maxQty') return?

Practice exercise

Build a mini bill: a select of dishes, each option with a data-price, and a quantity box. When "Calculate" is clicked, show "2 × Plain dosa = ₹140" in a paragraph.

Show a hint

Get the selected option with $('#dish').find(':selected'), then read .data('price') and .text() from it.

Show the solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Exercise: get and set</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <label for="dish">Dish</label>
  <select id="dish">
    <option value="idli" data-price="40">Idli (2 pcs)</option>
    <option value="dosa" data-price="70">Plain dosa</option>
    <option value="parotta" data-price="60">Parotta</option>
  </select>
  <label for="qty">Qty</label>
  <input id="qty" type="number" min="1" value="2">
  <button id="calc" type="button">Calculate</button>
  <p id="bill">Choose a dish.</p>

  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <script>
$('#calc').on('click', () => {
  const $option = $('#dish').find(':selected');
  const price = $option.data('price');
  const qty = Number($('#qty').val()) || 1;

  $('#bill').text(`${qty} × ${$option.text()} = ₹${qty * price}`);
});
  </script>
</body>
</html>

Progress is saved in this browser only.