Javascript manipulate contents by class name like ID

Most of us use ID to access or manipulate html DOM, But it can be done with class name which is little bit tricky. I have done it on one of my firefox plugin project.

var target_class = document.getElementsByClassName("div_content")[0];// Search the class
clearChildNodes(target_class);//Remove Child nodes of the class

var div1 = document.createElement("div");//create a new element
div1.setAttribute('class', 'child_div1');// Add class name to the newly created element

target_class .appendChild(div1);// Append the new element to the target div

function clearChildNodes(node) {
    if (node.childNodes.length > 0) {
        while(node.hasChildNodes()) {
    return node;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s