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:
TITLE1 clickableDIVs (not nested and not possible to nest)TITLE1 shows the previously hidden DIVs againDIVs that follow a TITLE up to a next TITLE (excluding)The Solution may use jQuery or such frameworks.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With