mroesler
mroesler

Reputation: 98

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:

The Solution may use jQuery or such frameworks.

Upvotes: 3

Views: 142

Answers (3)

James Coyle
James Coyle

Reputation: 10418

Would be much easier if you could wrap the title1 and div-# elements in one div. Then you could detect a click on title1, grab the parent then hide all of the children but the title div.

Something like this:

<div>
    <div class="title">Toggle divs</div>
    <div id="div1">Div1</div>
    <div id="div2">Div2</div>
    <div id="div3">Div3</div>
</div>
<div>
<div class="title">Toggle divs</div>
    <div id="div1">Div4</div>
    <div id="div2">Div5</div>
    <div id="div3">Div6</div>
</div>      

$(document).ready(function() {
    $('.title').click(function() {
       $(this).parent().children().not('.title').toggle(1000); 
    });
});

That is the solution I would use as it groups the elements logically: better for SEO and readability of code.

http://jsfiddle.net/WBH7C/

However, if the HTML cannot be edited then a solution like this would have to suffice:

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

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

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

Upvotes: 10

nnnnnn
nnnnnn

Reputation: 150080

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.

Upvotes: 2

Related Questions