Riccardo Riccardo - 3 months ago 9
jQuery Question

jQuery count nested buttons in nested and (initially) hidden DIVs

I have some PHP code generating HTML and depending on some conditions in some DIVs some buttons may be dynamically created using jQuery (after document load). The DIVs that may contain buttons, have an initial css hidden state.

While the containing DIVs are hidden I need to:


  • Count how many buttons are there

  • In case there's only one button, return id of the button



HTML

<div id="row-buttons">
<div> <!-- dynamically generated unknown id -->
<div id="classes-buttons-placeholder" style="display: none;">
<!-- a DIV that may contain x buttons dynamically generated -->
</div>
<div style="clear:both"></div>
<div id="subjects-buttons-placeholder" style="display: none;">
<div>
<!-- another DIV that may contain x buttons dynamically generated -->
<button id="Music" class="subjects-button"> Music</button>
</div>
</div>
</div>
</div>


In the example above, how can I verify if is there only one button and in this case return the id?

Answer

Try this code

$(function(){
    $("div[id*='-buttons-placeholder']:hidden").each(function(){
    var buttons = $(this).find("button");
    if(buttons.length == 1) {
        alert("Button inside " + $(this).attr("id") + ": " + buttons.attr("id"));
    }
  });
});

Gives output like Button inside subjects-buttons-placeholder: Music

JSFiddle: https://jsfiddle.net/vnathalye/bk4wbp6u/