Doubling breaks after removing <br> and leaving just text
After I perform following:
var noTags = document.createElement("DIV");
noTags.innerHTML = html;
noTags.textContent // <- I put this into any textarea
and this text:
text test <br><br> this text
Turns into this text:
text test
this text
Some how I get extra break. And they just keep on commin开发者_运维知识库g every time I do the above javascript. Please help :-(
When you assign html to the innerHTML property the browser will interpret that string based on the DOCTYPE set for the page. You will be at the mercy of the parser that the browser implemented for that DOCTYPE and the browser's implementation of said standard; read another way, "you will be guaranteed to get different results on different browsers".
That being said each browser will interpret the following HTML slightly differently.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Testing textcontent</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" >
</head>
<body>
<form action="">
<textarea id="onlyText" rows="5" cols="40"></textarea>
<script type="text/javascript">
/*<![CDATA[*//*---->*/
var html = "text text <br><br> text";
var noTags = document.createElement("DIV");
noTags.innerHTML = html;
// Retrieve text from html
var textContent = "";
var oe = document.getElementById("onlyText");
if (oe.innerText == undefined) {
textContent = noTags.textContent;
} else {
textContent = noTags.innerText;
}
alert("DEBUG: textContent = " + textContent);
oe.innerHTML = textContent;
/*--*//*]]>*/
</script>
</form>
</body>
</html>
Welcome to the interwebs. Your code will vary.
You have two breaks in there, why wouldn't you expect there to be two lines?
Breaks are usually done as a single closed tag, too. <br/>
instead of <br>
.
精彩评论