removing a class in javascript

RupertA
RupertA used Ask the Experts™
on
Hi, on the css I have two classes as follows...

.list_menu a {
display: block;
padding: 12px 0px;
background: #e1e1e1;
text-decoration: none;
}

.list_menu a:hover {
background: #d4d4d4;
background-repeat:no-repeat;
width:100%;
}

I want to remove them both and add my own Selected state when you click my div, I am using the following javascript function when you click, but it doesn't work, am I referencing the classes wrongly? Thanks.

function addMySelectedState()
{
var nameElem1 = document.getElementById("option1");
nameElem1.classList.remove("list_menu a");
nameElem1.classList.remove("list_menu a:hover");
nameElem1.classList.add("list_menu_selected");
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2017
Commented:
You are already have done.I added a onclick event to execute the function and I had made some changes in your js code:
HTML
<div class="list_menu" id="option1" onclick="addMySelectedState();"><a href=""></a></div>

Open in new window

JS
function addMySelectedState()
{
var nameElem1 = document.getElementById("option1");
nameElem1.classList.remove("list_menu");
nameElem1.classList.remove("a:hover");
nameElem1.classList.add("list_menu_selected");
}

Open in new window

Banshi lal dangiFull Stack Developer
Commented:
Please try below one, by just replacing the classname, instead of removing first one and adding the new class.
function addMySelectedState()
{
document.getElementById("option1").className = "list_menu_selected";
}

Open in new window

Author

Commented:
Hi there, both actually work, I wasn't referring to the classes correctly, which is why it was not working! Thanks.

Author

Commented:
Thanks!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial