Skip to content Skip to sidebar Skip to footer

Twitter Bootstrap Accordion Feature

Working with Bootstrap and JavaScript and I am using it as an accordion format - once clicked on the collapsed div it will open and show the items within the div based on the id.

Solution 1:

You'd need to bind to the show event on the accordion elements and perform your check there, from your classes I'm assuming your using Bootstrap v2.3.2:

$('.accordion .collapse').on('show', function () {
    var $inner = $(this).find('.accordion-inner');
    if($inner.is(':empty')){
        $inner.html('No items here');
    }   
});

Demo fiddle

Note that the :empty selector is very picky, it will not work if there's any white space between the opening and closing tags of .accordion-inner.

You may also use if(!$.trim($inner.html())) to check if the element is empty or as @JL suggested check the length of the children elements just beware that text nodes are not treated like children, so a div with only text would be considered empty

Solution 2:

Do you have jQuery installed? You can check if a <div> has children like this:

if ($('#divId').children().length == 0) {
     $('#divId').append("no items here");
}

If you don't have jQuery:

if (!document.getElementById('divId').hasChildNodes()) {
    document.getElementById('divId').innerHTML = "no items here";
}

Based on your edit, I think we're inspecting accordian-inner for children. If so, give it an ID and substitute that into our code. Note: You don't need a <div> to contain our "no items" message...the message will get printed with javascript (Plus, if you have a <div> there, then you've in effect added a child and the message no longer applies). Change your HTML to this:

<divclass='accordion-group'><divclass='accordion-heading'> Group 1 </div><divclass='accordion-body'><divid='innerId'class='accordion-inner'><!-- Remove the 'element' div --></div></div></div>

Then:

if (!document.getElementById('innerId').hasChildNodes()) {
    document.getElementById('innerId').innerHTML = "no items here";
}

Post a Comment for "Twitter Bootstrap Accordion Feature"