SyntaxStudy
Sign Up
jQuery jQuery DOM Manipulation Basics
jQuery Beginner 4 min read

jQuery DOM Manipulation Basics

The Document Object Model represents the structure of a web page as a tree of nodes. jQuery wraps the browser's DOM API in a consistent, chainable interface, letting you read, create, move, and delete elements with far less code than raw JavaScript.

Reading Content

.text() returns the combined text content of all matched elements — HTML tags stripped. .html() returns the inner HTML including markup. Both methods accept a value argument to set content, and both sanitise or preserve HTML depending on which you call.

Setting Content

.text(val) sets plain text, automatically escaping any HTML characters so user input cannot inject markup. .html(val) sets raw HTML — powerful but use it only with trusted content to avoid XSS vulnerabilities.

  • .text() — safe for user-supplied content
  • .html() — for trusted HTML strings
  • .val() — for form element values
  • .attr(name) — read an attribute
  • .attr(name, val) — write an attribute

All setter methods return the jQuery object, enabling method chaining: $('p').text('Hello').addClass('intro').

Example
// Read text and HTML
var txt  = $('#article').text();
var html = $('#article').html();

// Set text safely (escapes HTML)
$('#output').text('<script>alert(1)</script>'); // renders as text

// Set HTML
$('#widget').html('<strong>Updated!</strong>');

// Get / set a form value
var name = $('#name-input').val();
$('#name-input').val('Jane Doe');

// Get / set an attribute
var href = $('a.logo').attr('href');
$('img.avatar').attr('alt', 'User avatar');
Pro Tip

Use .text() when dealing with user input to prevent XSS — it escapes HTML entities automatically.