skip to Main Content

I have the following structure:

<li class="header group1"></li>
<li class="group1"></li>
<li class="group1"></li>
<li class="group1bottom"></li>

<li class="header group2"></li>
<li class="group2"></li>
<li class="group2"></li>
<li class="group2bottom"></li>

.. and so on

I get the headers:

let headers = $('.header');

then I need to loop through each of the headers elements, extract the other class containing the groupx, and match each of it with it’s corresponding groupxbottom:

headers.each(function() {
   // hide each groupxbottom element
});

I’ve tried a few attempts using $(this).classList[0] with regex to extract the specific class but could not get the correct result

2

Answers


  1. You can do it like this:

    $('.header').each(function() {
      var n = $(this).attr("class").match(/group(d+)/)[1];
      $(`.group${n}bottom`).hide();
    })
    

    var n = $(this).attr("class").match(/group(d+)/)[1]; will extract the number from the corrosponding groupX class

    Demo

    $('.header').each(function() {
      var n = $(this).attr("class").match(/group(d+)/)[1];
      $(`.group${n}bottom`).hide();
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <li class="header group1">header</li>
    <li class="group1">group1</li>
    <li class="group1">group1</li>
    <li class="group1bottom">group1bottom</li>
    
    <li class="header group2">header</li>
    <li class="group2">group2</li>
    <li class="group2">group2</li>
    <li class="group2bottom">group2bottom</li>
    Login or Signup to reply.
  2. Array.from(document.querySelectorAll('li.header')).forEach(el1 => {
      const arr = (el1.className).split(' ');
      const cl = arr[1] + 'bottom';
      Array.from(document.querySelectorAll('li.' + cl)).forEach(el2 => {
        el2.style.display = 'none';
      });
    });
    <ul>
      <li class="header group1">header group1</li>
      <li class="group1">group1</li>
      <li class="group1">group1</li>
      <li class="group1bottom">group1bottom</li>
    
      <li class="header group2">header group2</li>
      <li class="group2">group2</li>
      <li class="group2">group2</li>
      <li class="group2bottom">group2bottom</li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search