/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Create Element and Add HTML

Hello, I’m trying to create DIV, add some HTML to the DIV, then append it to another DIV.

Here’s a basic example:

[CODE]<!doctype html>

<html>
<head>
<meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />
<title>Title</title>
<meta name=”language” content=”en” />
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js”></script>
<script type=”text/javascript”>
//<![CDATA[
function addElement() {
var wrap = document.getElementById(‘wrap’);

// with createTextNode
var newDiv = document.createElement(‘div’);
var text = document.createTextNode(‘newDiv text’);
newDiv.appendChild(text);
wrap.appendChild(newDiv);

// with innerHTML
var newDiv2 = document.createElement(‘div’);
var theHtml = ‘<p>newDiv2 html</p>’;
newDiv2.innerHTML = theHtml;
wrap.appendChild(newDiv);

}
//]]>
</script>
</head>
<body>
<div id=”wrap”></div>
<input type=”button” value=”Add DOM Element” onclick=”addElement()” />
</body>
</html>[/CODE]

The createTextNode approach works. Why doesn’t the innerHTML example work? Can you not set the innerHTML of a newly created element?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@DanInMASep 15.2011 — perhaps try doing the innerHTML after the append?

Also I notice you are loading the Jquery framework. Are you using it for other purposes on the page? I'm just asking becuase it's much simpler to do in jQ than plain JS.
Copy linkTweet thisAlerts:
@cbVisionauthorSep 15.2011 — Whoops, foolish mistake. I was appending the same child twice ...
[CODE]
// with innerHTML
var newDiv2 = document.createElement('div');
var theHtml = '<p>newDiv2 html</p>';
newDiv2.innerHTML = theHtml;
[B]wrap.appendChild(newDiv2);[/B]
[/CODE]


Thanks DanInMA ... jQuery is there simply because it's in my default template ?. I just didn't strip it out for this example.
×

Success!

Help @cbVision spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...