Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to set text in tag with JavaScript?
In JavaScript, you can set text in HTML tags using various methods. This tutorial shows different approaches including jQuery and vanilla JavaScript.
Using jQuery .html() Method
First, create a <strong> element with an ID attribute:
<strong id="strongDemo">Replace This strong tag</strong>
Then use jQuery to set the text content:
$(document).ready(function(){
$("#strongDemo").html("Actual value of 5+10 is 15.....");
});
Complete jQuery Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Text in Tag</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<strong id="strongDemo">Replace This strong tag</strong>
<script>
$(document).ready(function(){
$("#strongDemo").html("Actual value of 5+10 is 15.....");
});
</script>
</body>
</html>
Using Vanilla JavaScript
You can achieve the same result without jQuery using pure JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Text with JavaScript</title>
</head>
<body>
<strong id="strongDemo">Replace This strong tag</strong>
<p id="paragraph">Original paragraph text</p>
<script>
// Using innerHTML
document.getElementById("strongDemo").innerHTML = "Text set with innerHTML";
// Using textContent (safer for plain text)
document.getElementById("paragraph").textContent = "Text set with textContent";
</script>
</body>
</html>
Methods Comparison
| Method | Library Required | HTML Content | XSS Safe |
|---|---|---|---|
| jQuery .html() | Yes | Yes | No |
| innerHTML | No | Yes | No |
| textContent | No | No | Yes |
Key Points
- Use
textContentfor plain text to prevent XSS attacks - Use
innerHTMLor jQuery's.html()when you need to insert HTML markup - Always ensure elements exist before trying to modify them
- jQuery provides cross-browser compatibility but adds overhead
Output
Conclusion
You can set text in HTML tags using jQuery's .html() method or vanilla JavaScript's innerHTML and textContent properties. Choose textContent for plain text and innerHTML for HTML content.
Advertisements
