JavaScript: Remove/Add Class Attribute

javascript-736400_640

I love jQuery because it helps simplify JavaScript. However, I needed to remove a class attribute from one menu item in my HTML, and add that class to another menu item. Easy with jQuery’s .addClass() and .removeClass(), right? BUT I didn’t want to add the entire jQuery library to my page just for this reason! So, like any self-respecting web designer, I googled it.

My final results:

function changeClass(){
    document.getElementById("menu_list").getElementsByTagName("li")[0].removeAttribute("class");
    document.getElementById("menu_list").getElementsByTagName("li")[3].setAttribute("class","selected");
}
window.onload = changeClass();

And it worked! A little JavaScript knowledge (and Google) can go a long way in improving page performance while adding enhancement.

On my journey to learn vanilla JavaScript, this small accomplishment was a big deal.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s