Riccardo
Riccardo

Reputation: 2216

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:

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?

Upvotes: 0

Views: 71

Answers (2)

Vaimeo
Vaimeo

Reputation: 1138

first of all itertate over each repeated div and then under div find button and return id

$('.master-divs').each(function(){
    
  b = $(this).find('button');
  if(b.length>0){
  button_id= b.attr('id');
    alert(button_id);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row-buttons">
    <div> <!-- dynamically generated unknown id --> 
        <div id="classes-buttons-placeholder"  class="master-divs" style="display: none;">
            <!-- a DIV that may contain x buttons dynamically generated  -->
        </div>
        <div style="clear:both"></div>
        <div id="subjects-buttons-placeholder" class="master-divs" 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>

Upvotes: 0

Vivek Athalye
Vivek Athalye

Reputation: 2979

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/

Upvotes: 1

Related Questions