In browsers that support getElementsByClassName
, you can do this:
var parents = document.getElementsByClassName("parent");
for (i=0; i<parents.length; i++){
var child = document.createElement("div");
child.setAttribute("class","child");
parents[i].insertBefore(child, parents[i].firstChild);
parents[i].appendChild(child);
}
getElementsByClassName
is supported by Chrome, Firefox 3+, as well as recent versions of Opera, and Safari. (see http://www.quirksmode.org/dom/w3c_core.html#fivemethods). Unfortunately it is not currently supported by any version of Internet Explorer.
Of course, you can write your own version of getElementsByClassName
that works in IE. (Basically it just needs to cycle through each element and add it to the collection if its class attribute matches the specified value.) Or you can get someone else to write it for you, either by using code you find online or just using a framework as prodigitalson suggests.