Riccardo Riccardo - 1 year ago 85
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


<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 style="clear:both"></div>
<div id="subjects-buttons-placeholder" style="display: none;">
<!-- another DIV that may contain x buttons dynamically generated -->
<button id="Music" class="subjects-button"> Music</button>

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

Answer Source

Try this code

    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/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download