Home > OS >  How to change icon by clicking on the div not only the icon
How to change icon by clicking on the div not only the icon

Time:10-17

Following code changes icon by clicking on the icon but how do I make it so that icon change by clicking on anywhere in the div or clicking on the link which is in the same div as the icon.

html:

<div >
    <i  onclick="changeIcon(this)" ></i>
    <a  href="#">addon</a>
</div>

JavaScript:

changeIcon = (icon) => icon.classList.toggle("fas")

CodePudding user response:

I would use the event.target to get the parent node and then query the i element using e.target.parentNode.querySelector('i') this will get the target element, then use .classList.toggle("fas") to toggle on click.

Also I recommend using an eventListener click over inline HTML onclick attribute for your function callback.

const btn = document.querySelector('.btn');

const changeIcon = (e) => e.target.parentNode.querySelector('i').classList.toggle("fas");

btn.addEventListener('click', changeIcon);
.btn {
  border: solid 1px black;
  width: 200px;
  padding: 2px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" rel="stylesheet"/>
<div >
  <i ></i>
  <a  href="#">addon</a>
</div>

CodePudding user response:

Try this:

<div  onclick="changeIcon(this)">    
    <i ></i>
    <a  href="#">addon</a>
</div>

This will trigger your function whenever you click inside the div.

  • Related