I am learning this stuff so this is my most simple script:
var t = document.createElement("table"),
tb = doc开发者_开发问答ument.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...
Try using td.innerHTML
instead. That way you can pass your tags as markup without worry.
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);
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/
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.
精彩评论