Jquery Html in JavaScript
? jQuery HTML Manipulation in JavaScript
What is jQuery HTML?
jQuery provides easy methods to get and set the HTML content inside DOM elements.
Helps dynamically update page content without rewriting complex DOM code.
Common jQuery HTML Methods
1. Get HTML Content
const content = $("#myDiv").html();console.log(content);Returns the inner HTML of the first matched element as a string.
2. Set HTML Content
$("#myDiv").html("<p>New content</p>");Replaces the inner HTML of all matched elements with the given HTML string.
Can include tags, scripts, etc.
3. Get Text Content
const text = $("#myDiv").text();console.log(text);Returns the text content of the element, stripping out all HTML tags.
4. Set Text Content
$("#myDiv").text("Just plain text");Sets the text content, escaping any HTML.
Example: Change Content on Button Click
<div id="content">Original content</div><button id="btn">Change Content</button><script> $("#btn").click(function() { $("#content").html("<b>Bold new content!</b>"); });</script>Important Notes
Using
.html()with user input can be dangerous (XSS risk). Sanitize inputs before inserting..text()is safer if you want to prevent HTML rendering.
Summary Table
| Method | Gets or Sets | Description |
|---|---|---|
.html() | Both | Get/set HTML content (with tags) |
.text() | Both | Get/set plain text content |
Want me to help with jQuery HTML and security tips or how to use .html() with event delegation?