简体   繁体   中英

How to toggle elements' class from an `onClick` event (from jQuery to pure JS)?

I want to toggle a css class on all elements with the same class, on click of another element.

I had it working with jQuery but need to switch to pure JavaScript.

The jQuery version that works:

$(function() {
  $("#logo").click(function() {
    $(".grey").toggleClass("white", 1000);
    $(".red").toggleClass("orange", 1000);
  });
});

When you click on the element with id="logo" , everything with class="grey" toggles white class and everything with class="red" toggles orange .

Update with new problem!

I'm using @Vektor's code which works well — except on the iPhone 5 where nothing happens. (It works in my iPhone 12 and 7.) Simplified code for trials:

<body>
    
<div id="logo"  class="grey"><p class="red">Hello.</p>
</div>

<script>

    const logo = document.getElementById('logo');
    
    logo.addEventListener('click', () => {
        const grey = document.querySelectorAll('.grey');
        const red = document.querySelectorAll('.red');
        grey.forEach(e => e.classList.toggle('white'));
        red.forEach(e => e.classList.toggle('orange'));
    }, false);
</script>
</body>
body{background-color: #000000;}
div#logo{
  position:fixed;
  top:0;
  left:0;
  height: 100vh;
  width:30vw;
  cursor: pointer;
}
.red{background-color:#4C0000;}
.orange{background-color:#d69215}
.grey{background-color:#485055;}
.white{background-color:white;}

I read adding cursor:pointer would fix JavaScript not functioning on non-traditional clickable elements for older iPhone browsers. It didn't.

first grab the "id". Then Listen for a "click" event on that. When click occurs grab the all "white" class elements first. "queryselectorAll" returns an array-like NodeList , so you can use "forEach" array method on that. Then iterate the all elements one by one. Same logic goes for "red" class elements.

 let  logo = document.getElementById('logo');

    logo.addEventListener('click', ()=>{
        let grey = document.querySelectorAll('.grey');
        grey.forEach((e)=>{
            e.classList.toggle('white')
        })
        let red = document.querySelectorAll('.red');
        red.forEach((e)=>{
            e.classList.toggle('orange')
        })
    })

Firstly, select the logo element by its id attribute. Register a click event listener on it to trigger the procedure. The event handler function will select all the elements containing the grey & red class names producing a list of nodes, iterate over them, and for each of those elements, toggle the white & orange class names in the list of classes.

 const logo = document.getElementById('logo'); logo.addEventListener('click', () => { const grey = document.querySelectorAll('.grey'); const red = document.querySelectorAll('.red'); grey.forEach(e => e.classList.toggle('white')); red.forEach(e => e.classList.toggle('orange')); }, false);
 body { background-color: #666; }.grey { color: #bbb; }.red { color: red; }.white { color: white; }.orange { color: orange; }
 <button id="logo">LOGO!</button> <p class="grey">Hello World</p> <p class="red">Hello World</p> <p class="grey">Hello World</p> <p class="red">Hello World</p> <p class="grey">Hello World</p>

I hope this solves your problem.

document.querySelector , addEventListener and className can be used to achieve the same.

  • Find parent element using document.querySelector
  • addEventListener for click on parent
  • When click is detected, find child element using document.querySelector and update its className .

Something like this:

 const parent = document.querySelector(".parent"); parent.addEventListener("click", function() { const oldChild = document.querySelector(".oldChild"); oldChild.className = "newChild" });
 .container { position: relative; width: 100vw; height: 100vh; background-color: yellow; }.parent { position: absolute; background-color: green; width: 250px; height: 250px; z-index: 2; }.oldChild { background-color: red; top: 100px; left: 100px; width: 25px; height: 25px; z-index: 2; }.newChild { background-color: blue; top: 100px; left: 100px; width: 25px; height: 25px; z-index: 2; }
 <div class="container"> <div class="parent" > Click on green area <div class="oldChild"></div> </div> </div>

There is a .toggle method on classList , so in your onclick handler, you can simply do the following:

document.querySelector('.grey').classList.toggle('white')
document.querySelector('.red').classList.toggle('orange')

Here's an example using classList.replace .

 document.addEventListener(`click`, handle); function handle(evt) { if (evt.target.id === `toggle`) { const current = evt.target.dataset.currentcolor; let colors = [`green`, `red`]; colors = current === `red`? colors.reverse(): colors; document.querySelectorAll(`.${current}`).forEach(el => el.classList.replace(...colors) ); evt.target.dataset.currentcolor = colors[1]; } }
 .green:before { content: 'Green'; color: green; }.red:before { content: 'Red'; color: red; }
 <div class="green"></div> <div class="green"></div> <div class="green"></div> <div class="green"></div> <button id="toggle" data-currentcolor="green">toggle color</button>

simplification of javascript is jquery so dont need to do it in hard way friend.

    var grey = document.getElementByClassName("grey");
   grey.classList.toggle("white");

   

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM