I have the following structure:
<li ></li>
<li ></li>
<li ></li>
<li ></li>
<li ></li>
<li ></li>
<li ></li>
<li ></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
CodePudding user response:
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 >header</li>
<li >group1</li>
<li >group1</li>
<li >group1bottom</li>
<li >header</li>
<li >group2</li>
<li >group2</li>
<li >group2bottom</li>
CodePudding user response:
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 >header group1</li>
<li >group1</li>
<li >group1</li>
<li >group1bottom</li>
<li >header group2</li>
<li >group2</li>
<li >group2</li>
<li >group2bottom</li>
</ul>