Query - Content API reference for Query methods related to element content file-text Guide

Query - Content

Content methods in Query allow you to manipulate content accessing form data, text and html.

Value

Gets or sets the value of form elements.

Syntax

Get

$('input').value();

Set

$('input').val(newValue)
NameTypeDescription
newValueanyThe new value to set

Alias

value is also available as val

$('input').val(); // identical;

Returns

Get

Query object (for chaining).

Set

The value of the first element in the set.

Usage

Geting a Value

// Get the value of an input
const inputValue = $('input').val();
console.log(inputValue);

Setting a Value

// Set the value of an input
$('input').val('New value');

Text

Gets or sets the text content of elements.

Syntax

Get

$('p').text()

Set

$('p').text(newText)
NameTypeDescription
newTextstringThe new text content to set

Returns

Get

The combined text content of all elements in the set.

Set

Query object (for chaining).

Usage

Getting Text

// Get the text of an element
const buttonText = $('button').text();
console.log(buttonText);

Setting Text

// Set the text of an element
$('button').text('Click me!');

HTML

Syntax

Get

$('.container').html()

Set

$('.container').html(newHtml)
NameTypeDescription
newHtmlstringThe new HTML content to set

Returns

Get

The HTML content of the first element in the set.

Set

Query object (for chaining).

Usage

Getting HTML

// Get the HTML content
const containerHtml = $('.container').html();
console.log(containerHtml);

Setting HTML

// Set the HTML content
$('.container').html('<p>New content</p>');

Outer HTML

Difference from HTML - Outerhtml returns the element including its own tag

Syntax

Get

$('.element').outerHTML()

Set

$('.element').outerHTML(newHtml)
NameTypeDescription
newHtmlstringThe new outer HTML content to set

Returns

Get

  • Single Element - The outer html of that element.
  • Multiple Elements - An array of outer html , one for each matched element.

Set

Query object (for chaining).

Usage

Getting Outer HTML

// Get the outer HTML
const elementOuterHtml = $('.element').outerHTML();
console.log(elementOuterHtml);

Setting Outer HTML

// Set the outer HTML
$('.element').outerHTML('<div class="new-element">Replaced content</div>');

Text Node

Versus text() - text will return text content recursively of nested nodes while textNode will only return the text content of the selected node, in some cases this distinction can be essential.

Syntax

Get

$('p').textNode()

Returns

Get

The combined text content of immediate text node children.

Usage

Getting Text Node Content

// Get only the immediate text content, ignoring nested elements
const immediateText = $('p').textNode();
console.log(immediateText);