Here's my on click function.
function toggleActiveClass(e){
console.log(e);
}
here's where i call the function
<a href="#" onclick="toggleActiveClass(this)" class="link--no-decor link--dark">
here's the output it returns in the console
<a href="#" onclick="toggleActiveClass(this)" class="link--no-decor link--dark">
<li>
<div class="menu-item menu-item--google menu-item--radio">
<span>...</span>
<span class="va-middle">
Personal info
</span>
</div>
</li>
</a>
i want to add class "active" in the div tag inside that anchor tag like this.
<a href="#" onclick="toggleActiveClass(this)" class="link--no-decor link--dark">
<li>
<div class="menu-item menu-item--google menu-item--radio active">
<span>...</span>
<span class="va-middle">
Personal info
</span>
</div>
</li>
</a>
tried using this
function toggleActiveClass(e){
e.target.childNodes[1].addClass("active");
}
but it didn't work. how do i add the class active to div? using javascript.
It does not work because addClass
is not a method of DOM nodes .
You need to change the class list:
function toggleActiveClass(link) { let div = link.querySelector('.menu-item'); div.classList.toggle('active'); }
.active { color:red; }
<a href="#" onclick="toggleActiveClass(this)" class="link--no-decor link--dark"> <li> <div class="menu-item menu-item--google menu-item--radio"> <span>...</span> <span class="va-middle"> Personal info </span> </div> </li> </a>
I have other div with active class i want to remove the active class from that div?
I'd have to know the rest of your document's structure, but at a guess:
function toggleActiveClass(link)
{
let currentActive = document.querySelector('.menu-item .active');
currentActive.classList.remove('active');
let newActive = link.querySelector('.menu-item');
newActive.classList.add('active');
}
First of all, you are passing this
to the function which does not have target
. To get the target property you have to pass event
. Then addClass()
is a jQuery method, to add class in vanilla JS, you should use classList.add()
. Though you should use toggle()
like the following way:
function toggleActiveClass(el){ //el.querySelector('div').classList.add("active"); el.querySelector('div').classList.toggle("active"); }
.active{ color:red; }
<a href="#" onclick="toggleActiveClass(this)" class="link--no-decor link--dark"> <li> <div class="menu-item menu-item--google menu-item--radio"> <span>...</span> <span class="va-middle"> Personal info </span> </div> </li> </a>
Instead of this pass event
<a href="#" onclick="toggleActiveClass(event)" class="link--no-decor link--dark">
this will solve the issue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.