简体   繁体   中英

Why does jQuery.height() work on an id, but not on a class?

For example, I have 20 items all the same height, all the same class "some_class". The first item of the twenty has an id of "first_item".

When I do $('.some_class').height(); I get 0 (which is wrong). But when I do $('#first_item').height(); it works and I get a value.

This baffles me. Why might this be? I can't really share the web page because its a private page.

EDIT: Interesting to note that .width() works just fine, and I get the same value calling it on #first_item or '.some_class'.

Because you'll probably find that the class selector is returning more than one element. In this case, height() returns the value of the first element (this is consistent throughout the jQuery get methods); which is probably not the one you want.

If you want the height of each of the element, you should iterate over them with each;

$('.some_class').each(function () {
    var myHeight = $(this).height();
});

jQuery height docs;

Get the current computed height for the first element in the set of matched elements.

$('.some_class:eq(0)').height(); should give you the proper output.

It's a basic html/css stuff, you need to understand.

'class' defines specific type of elements. Description of the class will be defined with style associated with that class. So, class is used to provide style to multiple elements of same type. For example, 20 items mentioned by you have same class. (They can not have same id).

'id' is an unique identification of an HTML element. There can not be multiple elements having same 'id'. So, 'id' is used to provide style to one uniqe element. Ways of writing style for class 'myClass' and id 'myId' are as below.

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