计算div中存在的按钮数

时间:2018-08-17 12:46:12

标签: javascript jquery

我要计算javascript的div中存在的按钮数吗?

<div id='maindiv'>
    <button></button>
    <button></button>
    <button></button>
    <button></button>
    <button></button>
</div>

4 个答案:

答案 0 :(得分:4)

许多方式: JavaScript:document.querySelectorAll('#maindiv button')

JQuery:$('#maindiv button')

var buttons = document.querySelectorAll('#maindiv button')
console.log(buttons.length)
<div id='maindiv'> <button></button> <button></button> <button></button> <button></button> <button></button> </div>

答案 1 :(得分:3)

您可以在div中找到所有按钮并获取其长度

$(function(){
  var count = $('#maindiv button').length;
  console.log(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='maindiv'>
  <button></button>
  <button></button>
  <button></button>
  <button></button>
  <button></button>
</div>

答案 2 :(得分:0)

纯js:

const result = document.querySelectorAll('#maindiv button').length

console.log(result)
<div id='maindiv'> 
  <button></button> <button></button> <button></button> <button></button> <button></button> 
</div>

或所有孩子:

const result = document.getElementById('maindiv').children.length;

console.log(result)
<div id='maindiv'> 
  <button></button> <button></button> <button></button> <button></button> <button></button> 
</div>

答案 3 :(得分:0)

$(function(){ var totalDiv = $('#maindiv').children('button').length; consloe.log(totalDiv) });