Reputation: 2216
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?
Upvotes: 0
Views: 71
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
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