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
innerHTML adds text but not HTML tags
When using innerHTML in JavaScript, you need to ensure proper HTML string formatting and correct assignment. The innerHTML property parses and renders HTML tags when set correctly.
Common Issue: Building HTML Strings
When concatenating HTML strings with +=, make sure to build the complete HTML structure before assigning it to innerHTML.
<div id="numberList"></div>
<script>
var myNum = [1, 2, 3];
var myStr;
myStr = "<ul>";
for(var a in myNum) {
myStr += "<li>" + myNum[a] + "</li>";
}
myStr += "</ul>";
document.getElementById("numberList").innerHTML = myStr;
</script>
? 1 ? 2 ? 3
Correct vs Incorrect Assignment
Here's a comparison showing the correct way to use innerHTML with HTML tags:
<div id="demo1"></div>
<div id="demo2"></div>
<script>
// Correct: HTML tags are rendered
document.getElementById("demo1").innerHTML = "<strong>Bold Text</strong>";
// Incorrect: Using textContent instead - tags show as text
document.getElementById("demo2").textContent = "<strong>Bold Text</strong>";
</script>
Bold Text <strong>Bold Text</strong>
Key Points
| Method | Renders HTML? | Use Case |
|---|---|---|
innerHTML |
Yes | Adding HTML elements |
textContent |
No | Plain text only |
Conclusion
Use innerHTML to add HTML tags that will be rendered as elements. Ensure your HTML strings are properly formatted and use getElementById() or similar methods to target elements correctly.
Advertisements
