2

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?

1
  • 3
    you can do this .find( ".set_height, .fixed_height, .dynamic_height" ).first() Commented Nov 9, 2018 at 11:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

You should use .first() instead of [0] because you will prevent unexpected behavour errors.
Can not get [0] of undefined. You have the possibility of not found any element with selectors
returns undefined. The other implementation can return errors You have jsfiddle here with examples jsfiddle.net/xpvt214o/931724 @ThisGuyHasTwoThumbs The problem of this solution is that he's mixing js dom properties with jquery. If you are using jquery, you should profit all methods from jquery for avoid errors.
@segu ahh I see, dankes for explaining :) will rm my comments :)
@ThisGuyHasTwoThumbs no problem, just explaining a better approach of using jquery
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.