Skip to content Skip to sidebar Skip to footer

Hide All Element That Have Class= ' Contact ' And Keep Just 5 Items Javascript

Solution 2:

You can do this using Vanilla JS:

const contactElements = document.querySelectorAll('.contact')

contactElements.forEach((elem, i) => {
    // If i is less than or equal to 4, that means the current iteration is one of the first 5 elements.if (i > 4) {
        elem.style.display = 'none'// Or add a class// elem.classList.add('hidden')
    }
})

Solution 3:

You can do something like that:

//i want hide all element that have class= ' contact ' and keep just 5 items using js or jQuerydocument.querySelectorAll('.hide')[0].addEventListener('click', function() { // click eventlet el2hide = document.querySelectorAll('.contact'); // the class we want to hidefor (var i=0; i < el2hide.length; i++) { 
        if (i > 4) { // start after 5
          el2hide[i].classList.add('hidden'); // hide them
        };
    }
});
a {color: blue; text-decoration: underline;}
.hidden {opacity: 0.1}
<divclass="text-center mt-4"><arole="presentation"type="button"class="btn btn-lg hide">click to "hide"</a></div><h1>Deom .contact elements:</h1><ol><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li><liclass="contact">contact</li></ol>

Solution 4:

I translated Rohit's answer to vanilla JS with the :nth-child(n+6) selector.

const contactElements = document.querySelectorAll('.contact:nth-child(n+6)');
const hideBtn = document.querySelector('#hide');

hideBtn.addEventListener('click', () => contactElements.forEach(elm => elm.style.display = 'none'));
.wrapper {
  margin: 20px;
  display: flex;
  flex-wrap: wrap;
}
.contact {
 padding: 12px;
 margin: 20px;
 background: #ccc;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonid="hide">Hide</button><divclass="wrapper"><divclass="contact">Thumbnail 1</div><divclass="contact">Thumbnail 2</div><divclass="contact">Thumbnail 3</div><divclass="contact">Thumbnail 4</div><divclass="contact">Thumbnail 5</div><divclass="contact">Thumbnail 6</div><divclass="contact">Thumbnail 7</div><divclass="contact">Thumbnail 8</div></div>

Post a Comment for "Hide All Element That Have Class= ' Contact ' And Keep Just 5 Items Javascript"