简体   繁体   中英

jQuery - Get CSS value from element

I am searching a container to grab the padding of a matched element like this..

 padding = $( ".container" ).find( ".set_height" ).css( "padding-top" ); console.log(padding); 
 .set_height { padding-top:50px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="section"> <div class="match_height"> Section 1 </div> </div> <div class="section"> <div class="match_height"> Section 2 </div> </div> <div class="section"> <div class="set_height"> Section 3 </div> </div> </div> 

The set_height div could also potentially be fixed_height or dynamic_height

How can I modify the jQuery to search for one of those and stop when it finds one, so if there are multiples then it will just grab the value for the first one it finds?

http://api.jquery.com/multiple-selector/

You can pass a list of classes as a selector.

var padding = 0;
var items = $( ".container" ).find( ".set_height, .fixed_height, .dynamic_height");
if (items.length) {
    padding = items[0].style.paddingTop; 
}

EDIT

@segu is right (thanks), but it's not sufficient to just call first() , you have to check if the result of first().style is undefined , because calling first().style.paddingTop can trigger Uncaught TypeError: Cannot read property 'paddingTop' of undefined if no results are found. I just used length property instead.

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