If I wanted a quick-and-dirty HTML parser with good support and couldn't be bothered to write my own, innerHTML would be my first port of call. In fact, I've used it fairly extensively (as in my typing text script). However, for something as simple as this, I see no call to break the standards and lose XHTML support for the script.
Perhaps you should mention that, if you do it that way, you need to have at least a inside the id="myElement" element,
Possibly I should have done, but that was only an example, and obviously needs to be adapted for the OP's markup (or have the OP's markup adapted for it). There's probably currently no element with an ID of "myElement" in the markup either.
and that you cannot insert rich HTML content without considerably more code.
wentwooddownhill said "text" so I didn't even consider this worth mentioning. Furthermore, it's not exactly "considerably" more code, especially if we use an element-builder function:
Code:
function buildElement(nodeName, attributes) {
var v = document.createElement(nodeName);
if(attributes)
for(var x in attributes)
if(attributes.hasOwnProperty(x))
if(x !== "style")
v[x] = x;
else
for(var y in attributes.style)
if(attributes.style.hasOwnProperty(y))
v.style[y] = y;
for(var i = 2; i < arguments.length; ++i)
if(typeof arguments[i] === "string")
v.appendChild(document.createTextNode(arguments[i]));
else
v.appendChild(arguments[i]);
return v;
}
It becomes as simple as:
Code:
document.getElementById("myElement").appendChild(
buildElement("span", {
'id' : "mySpan",
'style' : {
'display' : "block",
'background-color' : "red"
}
},
"Some inner text")
);
Reflects the structure of the HTML fairly well, and is one heck of a lot neater than the horrible multi-line string that usually results from innerHTML.
Of course, that's kind of irrelevant anyway; wentwooddownhill should really already have elements created, and just hide/show them using Javascript (by setting and unsetting the CSS display property).
Bookmarks