最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Count number of divs inside a div - Stack Overflow

programmeradmin8浏览0评论
<div id="full">
        <?php $i=0; $j=1; foreach ($array as $image){ ?>
        <div id="image<?php echo $i;?>" class="img bg-img<?php echo $j;?>"><img src="<?php echo $image['image']; ?>" ></img></div>
        <?php $j++; $i++;} ?>           

    </div>

How do i get the number of divs contained by div id="full"?.

<div id="full">
        <?php $i=0; $j=1; foreach ($array as $image){ ?>
        <div id="image<?php echo $i;?>" class="img bg-img<?php echo $j;?>"><img src="<?php echo $image['image']; ?>" ></img></div>
        <?php $j++; $i++;} ?>           

    </div>

How do i get the number of divs contained by div id="full"?.

Share Improve this question edited Nov 23, 2011 at 20:02 Christian Rau 45.9k11 gold badges114 silver badges189 bronze badges asked Nov 23, 2011 at 15:36 Nathan TravisNathan Travis 1032 silver badges12 bronze badges 3
  • 2 I'd clarify whether you want only children divs (rich.okelly's solution), or ALL divs aka descendants (Shomz's solution) – John Strickler Commented Nov 23, 2011 at 15:40
  • 1 possible duplicate of How can I count the number of children? – Felix Kling Commented Nov 23, 2011 at 15:45
  • @JohnStrickler + for the ment; according to his code, there are only children divs, though – Shomz Commented Nov 23, 2011 at 15:49
Add a ment  | 

6 Answers 6

Reset to default 15

The following should do it:

$('#full > div').length

See here for jsFiddle

Try this:

$('div#full div').length;

You can use:

$('#full > div').length

docs on : http://api.jquery./size/

var divCount = $('#full').children('div').length;

you can get like this:

<div id="full">
<?php $total = count($array); ?>
<?php $i=0; $j=1; foreach ($array as $image){ ?>
        <?php $i=0; $j=1; foreach ($array as $image){ ?>
        <div id="image<?php echo $i;?>" class="img bg-img<?php echo $j;?>"><img src="<?php echo $image['image']; ?>" ></img></div>
        <?php $j++; $i++;} ?>           

</div>
var count= $("#full > div").size()

Now variable count will have the number of divs

I just realized that size() returns same as length. But using length, you avoid an extra method call. So go for length.

发布评论

评论列表(0)

  1. 暂无评论