Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamically insert entity without innerHTML?

Status
Not open for further replies.

jemminger

Programmer
Jun 25, 2001
3,453
US
i'm trying to insert an HTML entity into an element using DOM methods only. i'm having trouble getting entities to be parsed instead of being rendered as plain text, e.g. ">" should display as a right-angle-bracket ">", not the literal text ">". using innerHTML instead of nodeValue works, but i want to avoid non-DOM methods.

any ideas?

Code:
<html>
	<head>
		<title>test</title>

		<script type="text/javascript">
			function foo() {
				document.getElementById("somediv").firstChild.nodeValue = "&gt;";
			}
		</script>
	</head>

	<body>
		<form>
			<input type="button" value="foo();" onclick="foo();" />
			<div id="somediv">&nbsp;</div>
		</form>
	</body>
</html>

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
I faced this issue a few months ago... after thinking about it for a while, I reached the conclusion that as the character entities are for HTML, not JavaScript, you don't need to escape them.

I assumed that the JavaScript engine would do this translation for me when setting the value.

Of course, I can't prove that... but it sounded feasible enough ;o)

Dan

[tt]D'ya think I got where I am today because I dress like Peter Pan here?[/tt]
[banghead]

 
cloneNode() is the best I've come up with so far.

Code:
<script type="text/javascript">

function showTest() {
  var oSpan = document.getElementById("nDash");
  var oDiv = document.getElementById("testResponse");
  oDiv.appendChild(document.createTextNode("This ( "));
  oDiv.appendChild( oSpan.cloneNode(true) );
  oDiv.appendChild(document.createTextNode(" ) is a repro"));
}

</script>

<body onload="showTest();">
<h1>display html entitity</h1>
  <p>This is an html entitity ( <span id="nDash">&ndash;</span> ), the n-dash
  </p>
  <div id="testResponse"></div>
  <p>Test concluded.</p>
</body>

It's a bit cumbersome but manageable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top