PDA

View Full Version : DOM to create <p> and <span> tags



sniperman
02-11-2011, 04:12 PM
I'm hoping someone can help the brain freeze I've had in the past couple of hours. I am using the below code to create a text node and a span element.


onload=function(){
var root = document.getElementById('zonediv');
for(var i=0;i<D.length;i++){
root.appendChild(document.createTextNode(D[i][0]+' '))
var sp= document.createElement('span');
sp.appendChild(document.createTextNode(' '));
root.appendChild(sp);root.appendChild(document.createElement('br'))
}

I can't really style a text element directly inside a DIV without some kind of mark-up so I am trying to make the DOM create nodes in this order


<div id="zonediv"> // parent
<p> // need to replace text node with p element
<span>
<br>

I know it's probably easy, my brain just won't register at this time of night... so thanks in advance.

Nile
02-11-2011, 08:31 PM
var parentEl = document.getElementById("zonediv);
var pEl = document.createElement("p");
var spanEl = document.createElement("span");
var brEl = document.createElement("br");

spanEl.appendChild(brEl);
pEl.appendChild(spanEl);
parentEl.appendChild(pEl);

Is this what you mean?

sniperman
02-11-2011, 11:35 PM
Thanks, that was somewhat helpful.

Your example gave me a chance to look up some tutorials because I needed the text nodes to appear inside the <p> tags. After some good sleep and a couple of steely minutes I came up with this workable solution.


onload=function(){
var root = document.getElementById('zonediv');
for(var i=0;i<D.length;i++){
var p = document.createElement("p");
p.appendChild(document.createTextNode(D[i][0]+' '))
var sp= document.createElement('span');
sp.appendChild(document.createTextNode(' '));
root.appendChild(p);root.appendChild(sp);root.appendChild(document.createElement('br'))
}

I had to wrap the text around a paragraph node, and append it to the parent. DOM complexio.

Nile
02-13-2011, 12:10 AM
No problem, I'm glad to help :D

Here on DD, we like to keep things organized. In an effort to do so, you have the option to set a thread to resolved when an issue is fixed. To make the status of the thread resolved:
1. Go to your first post
2. Edit your first post
3. Click "Go Advanced"
4. In the dropdown next to the title, select "RESOLVED"