I was using innerHTML property in javascript and suddenly I got a problem that the content inside <p><h3>....</h3></p>
is not being fully replaced when applying .innerHTML
on <p>
tag in it. But when I make the same thing in a <div>
as <div><h3>....</h3></div>
it fully replaces the inner content. Can anyone tell me why is it happening?
See what's happening in this fiddle .
See full code below:
<html>
<head>
<title>innerHTML doubt</title>
<script type="text/javascript">
function changeContent(id){
document.getElementById(id).innerHTML="Content changed in id '"+id+"'.";
}
</script>
</head>
<body>
<p id="p1">
This content is in first <b>'p'</b> tag (can b fully replaced).
</p>
<button onclick="changeContent('p1')">Change upper content</button><hr/>
<p id="p2">
<h3>This content is in second 'p' tag with 'h3' tag inside (will not be replaced fully) </h3>
</p>
<button onclick="changeContent('p2')">Change upper content</button><hr/>
<div id="div1">
This content is in first 'div' (can b fully replaced).
</div>
<button onclick="changeContent('div1')">Change upper content</button><hr/>
<div id="div2">
<h3>This content is in second 'div' inside of 'h3'(will also b replaced fully)</h3>
</div>
<button onclick="changeContent('div2')">Change upper content</button>
</body>
</html>
Its happening because when you use <h3></h3>
or any heading tag within p
tag ,the closing tag gets out of scope.
Error when i validate code at W3C Markup Validator
See this Fiddle .In this fiddle you will see that in 2nd p
only the text outside and before <h3></h3>
will be replaced by innerHTML.That means <p>
gets closed before <h3></h3>
because using h3 within p is invalid .
Use CSS style similar to h3
for styling text inside p
tags. Demo Fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.