Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding certain DIVs (not nested unfortunately)

I am working with legacy code that is generated automatically and must comply to the following structure:

<div id="TITLE1"></div>
<div id="div-1"></div>
<div id="div-2"></div>
<div id="div-3"></div>
<div id="div-4"></div>
.... (there can be more divs here, IDs can vary as well) ...
<div id="TITLE2"></div>

What I want to do now is the following:

  • Make TITLE1 clickable
  • Once clicked hide all underlying DIVs (not nested and not possible to nest)
  • Another click on TITLE1 shows the previously hidden DIVs again
  • Only hide those DIVs that follow a TITLE up to a next TITLE (excluding)

The Solution may use jQuery or such frameworks.

like image 338
mroesler Avatar asked Feb 22 '26 01:02

mroesler


2 Answers

Try

$('div[id^=TITLE]').click(function(){
    $(this).nextUntil('div[id^=TITLE]').toggle();
})

Demo: Fiddle

The underlying logic is simple - Make divs with id starting with TITLE clickable by adding a click handler - to do this attribute starts with selector is used. Then find all divs between the clicked element and the next element with id starting with TITLE - this is done using .nextUntil() traversal method. Then .toggle() is used to hide/show the element

like image 64
Arun P Johny Avatar answered Feb 23 '26 16:02

Arun P Johny


Perhaps something like this:

$(document).ready(function() {
    $("body").on("click", 'div[id^="TITLE"]', function() {
        $(this).nextUntil('div[id^="TITLE"]').slideToggle();
    });
});

Demo: http://jsfiddle.net/cjZzG/

That is, whenever a div that has an id beginning with the text "TITLE" is clicked, use the .nextUntil() method to select every element up to the next such div and then toggle their visibility.

like image 33
nnnnnn Avatar answered Feb 23 '26 15:02

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!