简体   繁体   中英

how to add or remove class on li first child using javascript

I want to convert jquery code into javascript in which when window height is less than 50 then add or remove class not added on li first child but other li child class added or removed. show jquery code below

  $(window).scroll(function(){
      if ($(window).scrollTop() >=50) {
        $('.responsive-header .social-icons .social-icon li').not(':first-child').addClass('hidden');
        $('.responsive-header .social-icons .social-icon li').not(':first-child').removeClass('show');
      }
   });
window.onscroll = function(e) {
    if (e.target.scrollHeight > 50) {
        document.querySelectorAll(".responsive - header.social - icons.social - icon li:not(:first-child)").forEach(function (el) {
            el.classList.add('hidden');
            el.classList.remove('show');
        }) 
    }
};

I didn't test it but idea is like this

Since classes are being removed and added the most simplest and reliable way to exclude the first <li> is to give it a class and place it after the class that it's excluded from.

Use MediaQueryList interface to listen for viewport height changes and fire a callback function when the MQL matches the viewport height.

 // Create a MediaQueryList var mql = window.matchMedia('(max-height: 50px)'); // Add a listener to MQL mql.addListener(shortWin); /* - Callback function passes Event Object - Reference the <ol> - if the MQL matches the viewport height... - Add class .short to <ol> - Otherwise remove class .short */ function shortWin(e) { var list = document.querySelector('ol'); if (e.matches) { list.classList.add('short'); } else { list.classList.remove('short'); } } 
 .short li { background: magenta } /* This CSS selector will always override .short*/ .short li.first { background: initial; } 
 <ol> <li class='first'>ITEM</li> <li>ITEM</li> <li>ITEM</li> <li>ITEM</li> <li>ITEM</li> </ol> 

document.getElementById('share').addEventListener("click",show);
    function show(){
        var divs = document.querySelectorAll('#social-icons > li:not(.share)');
        for (var i = 0; i < divs.length; i++) {
            divs[i].classList.toggle("show");
            divs[i].classList.toggle("hidden");
        }
    }

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