Ran into a problem in JavaScript writing HTML code into innerHTML. Here is a very simple case I recreated. The problem is in the element style seems taking no effect, either using old font size or CSS style. The code has been tested on FireFox and Chrome in XAMPP localhost, and got same result. The text would be shown correctly but the style wouldn't. Any suggestion?
tDoc = document.getElementById('target');
tDoc.innerHTML = "<p><font size='+5'>";
tDoc.innerHTML += document.getElementById("srcBox").value;
tDoc.innerHTML += "</font></p>";
tDoc.innerHTML += "<p style='font-size:20px;'>";
tDoc.innerHTML += document.getElementById("srcBox").value;
tDoc.innerHTML += "</p>";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>JavaScript innerHTML not setting the element style</title>
</head>
<body>
<input type="text" name="ttBox" id="srcBox" value="My Title 2">
<div id="target">NA</div>
</body>
</html>
Don't append to innerHTML
in multiple steps like that. Each time you assign to innerHTML
it parses the element completely to create the new DOM. If there are missing closing tags, it adds them. So when you do
tDoc.innerHTML = "<p><font size='+5'>";
it's actually as if you did
tDoc.innerHTML = "<p><font size='+5'></font></p>";
Then your next addition is outside the <font>
tag, so it doesn't get the style.
Put everything into a single string and assign it to innerHTML
all at once.
tDoc = document.getElementById('target');
let html = "<p><font size='+5'>";
html += document.getElementById("srcBox").value;
html += "</font></p>";
html += "<p style='font-size:20px;'>";
html += document.getElementById("srcBox").value;
html += "</p>";
tDoc.innerHTML = html;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>JavaScript innerHTML not setting the element style</title>
</head>
<body>
<input type="text" name="ttBox" id="srcBox" value="My Title 2">
<div id="target">NA</div>
</body>
</html>