I am learning this stuff so this is my most simple script:
var t = document.createElement("table"),
tb = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
t.style.width = "100%";
t.style.borderCollapse = 'collapse';
t.border=1;
// note the reverse order of adding child
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);
// more code to populate table rows and cells
document.getElementById("theBlah").appendChild(t);
alert(t);
}
Now I want to add something that will be displayed in <td>, so I figured:
td.appendChild(document.createTextNode(title));
which works great...
but if title contains html, for example a simple bold tag, like so Hello<b> name!</b>
how do we do that?
I think we create a new element for <b> but... after that, i have no idea how to do it.
Just to clarify, I want the end result to be that Hello<b> name!</b> ends up in the TD tag like this:
<td>Hello<b> name!</b></td>
Please help!!
EDIT; Yes, I know I can do this via InnerHTML, but I need to do it this way to get it past Firefox AMO policies Sorry shoulda mentioned this earlier...
-
1you can try learning jQuery a very simple and highly effective javascript library jquery.comAnantha Sharma– Anantha Sharma2011年07月29日 03:18:16 +00:00Commented Jul 29, 2011 at 3:18
-
1JQuery is great for sure, but I think it's even better if people take the time to first learn more Javascript and DOM manipulation without it. Then you can still write be effective if JQuery isn't an option, and you have some idea what's happening under the hood of JQuery (or whichever JS library)Newtang– Newtang2011年07月29日 03:23:24 +00:00Commented Jul 29, 2011 at 3:23
4 Answers 4
Try using td.innerHTML instead. That way you can pass your tags as markup without worry.
Comments
You'd assign the innerHTML to the element you want to append.
td = document.createElement("td");
td.innerHTML = "<em>OMG!</em> I can has <strong>HTML<strong>!"
tr.appendChild(td);
Comments
Try:
var td = document.createElement("td");
var b = document.createElement("b");
b.appendChild(document.createTextNode(" name!"));
td.appendChild(document.createTextNode("Hello"));
td.appendChild(b);
Result: <td>Hello<b> name!</b></td>
Example: http://jsfiddle.net/hGF3e/
Comments
As the other folks have mentioned, the simplest thing you can do is:
td.innerHTML = "Hello<b> name!</b>";
You can also do:
var b = document.createElement('b');
b.appendChild(document.createTextNode(" name"));
td.appendChild(document.createTextNode("Hello"));
td.appendChild(b);
Also, just so you know, the <b> tag is technically deprecated. You should use <em> or <strong> instead.
5 Comments
b.appendChild(" name"); and the error is: Uncaught Error: NOT_FOUND_ERR: DOM Exception