Cover Image for jQuery html() method
100 views

jQuery html() method

The jQuery html() method is used to get or set the HTML content of selected elements. It allows you to retrieve the inner HTML of an element or update it with new HTML content dynamically.

The syntax for using the html() method is as follows:

To Get the Inner HTML:

$(selector).html();

To Set New HTML Content:

$(selector).html(newHTML);
  • selector: It is a string that specifies the elements to be selected.
  • newHTML (optional): It is a string representing the new HTML content that you want to set for the selected elements. If you omit this parameter, the html() method will act as a getter and return the current inner HTML of the selected elements.

Here’s an example of how you can use the html() method:

HTML:

<div id="myDiv">
  <p>This is the initial content.</p>
</div>

JavaScript:

// Get the current inner HTML of the div
var innerHTML = $('#myDiv').html();
console.log('Current HTML: ' + innerHTML);

// Set new HTML content for the div
$('#myDiv').html('<p>This is the updated content.</p>');

In the example, the html() method is used to get the current inner HTML of the div element with the ID “myDiv” using $('#myDiv').html(). The current HTML content is then logged to the console.

Then, the html() method is used again to set new HTML content for the div using $('#myDiv').html('<p>This is the updated content.</p>').

The html() method is commonly used when you want to manipulate the content of elements, such as updating text, inserting new elements, or displaying dynamic content fetched from external sources like APIs.

It is essential to be cautious when using html() with user-generated or untrusted content to avoid security vulnerabilities like cross-site scripting (XSS) attacks. To prevent such vulnerabilities, use proper sanitization or encoding when inserting content retrieved from users or external sources. Additionally, consider using safer methods like text() if you want to set plain text content instead of HTML content.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS