jQuery provides several methods to get and set content in HTML elements. Here are the main methods:
1. text()
Get content: Returns the combined text content of selected elements (excluding HTML tags)
Set content: Sets the text content of selected elements (HTML tags are escaped)
1 2 3 4 5 |
// Get text content let content = $('#element').text(); // Set text content $('#element').text('New text content'); |
2. html()
Get content: Returns the HTML content of the first matched element (including HTML tags)
Set content: Sets the HTML content of selected elements (HTML tags are rendered)
1 2 3 4 5 |
// Get HTML content let htmlContent = $('#element').html(); // Set HTML content $('#element').html('<strong>New HTML content</strong>'); |
3. val()
Get value: Returns the value of form elements (input, select, textarea)
Set value: Sets the value of form elements
1 2 3 4 5 |
// Get value let inputValue = $('#inputField').val(); // Set value $('#inputField').val('New value'); |
4. attr()
Get attribute: Returns the value of a specified attribute
Set attribute: Sets the attribute value
1 2 3 4 5 |
// Get attribute let href = $('#link').attr('href'); // Set attribute $('#link').attr('href', 'https://newurl.com'); |
5. prop()
Get property: Returns the value of a property (for boolean attributes like checked, disabled)
Set property: Sets the property value
1 2 3 4 5 |
// Get property let isChecked = $('#checkbox').prop('checked'); // Set property $('#checkbox').prop('checked', true); |
6. data()
Get data attribute: Returns the value of a data attribute
Set data attribute: Sets the data attribute value
1 2 3 4 5 |
// Get data attribute let user = $('#element').data('user'); // Set data attribute $('#element').data('user', {id: 123, name: 'John'}); |
7. append() / prepend()
Add content at the end or beginning of selected elements
1 2 3 4 5 |
// Append content $('#element').append('<p>Added at the end</p>'); // Prepend content $('#element').prepend('<p>Added at the beginning</p>'); |
8. after() / before()
Add content after or before selected elements
1 2 3 4 5 |
// Add after $('#element').after('<div>New element after</div>'); // Add before $('#element').before('<div>New element before</div>'); |
9. replaceWith()
Replace selected elements with new content
1 |
$('#element').replaceWith('<div>New content</div>'); |
10. empty() / remove()
empty(): Removes all child nodes and content from selected elements
remove(): Removes the selected elements themselves
1 2 3 4 5 |
// Empty content $('#element').empty(); // Remove element $('#element').remove(); |
These methods provide flexible ways to manipulate content in the DOM using jQuery. Choose the appropriate method based on whether you need to work with text, HTML, form values, or attributes.