简体   繁体   中英

Jquery retrieve width of specific div from list

I'm struggling to retrieve the width of a div in an array of divs with jquery. Normally I'd do something like this...

$("#divID").width()

Which would work fine, but I have to iterate through a list of divs this time, and this returns the error "Uncaught TypeError: $(...)[0].width is not a function"

$("#parentID .childClass")[0].width()
$("#parentID .childClass")[1].width()
etc...

And using .width (as an attribute instead of a function) just returns "undefined".

Any ideas what I'm doing wrong?

EDIT - apologies - I originally omitted the .childClass identifier which is what causes my jquery selection to correctly return a list of all divs. My question is really simply how to return the width of one such div

You have to use eq in order to get a div at specified index .Here is an example:

eq method reduce the set of matched elements to the one at the specified index.

 var length=$('.parentClass').length; for(i=0;i<length;i++){ console.log($('.parentClass').eq(i).width()); } 
 .parentClass{ width:50px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="parentClass"></div> <div class="parentClass"></div> 

Another solution is to use each() method.

$("#parentID .childClass").each(function(){
    //code
});

You can write a jQuery plugin to do this. Just find child elements within a parent element and locate the nᵗʰ item.

 (function($) { $.fn.nthChild = function(childSelector, n) { return this.find(childSelector).eq(n); }; $.fn.nthChildWidth = function(childSelector, n) { return this.nthChild(childSelector, n).width(); }; })(jQuery); console.log($('#parent-id').nthChildWidth('.child-class', 0)); console.log($('#parent-id').nthChildWidth('.child-class', 1)); 
 .as-console-wrapper { top: 0; max-height: 100% !important; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent-id"> <div class="child-class" style="width:200px"></div> <div class="child-class" style="width:300px"></div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM