Larry Maner Larry Maner - 3 months ago 45
jQuery Question

Running jQuery Script for Each Div on Page Load

I've been wracking my brain and searched through this site and others to figure out why the script I'm running only works on the first div that I run it on. I need this script to find all the instances of this class and modify its css. It's a vertically centering script.

<script type="text/javascript">
$(document).ready(function () {
$(".innerDiv").css('top', ($(".outerDiv").height() - $(".innerDiv").height()) / 2);

This is the example of the HTML it should be running on.

<div class="outerDiv" style="height:calc(100% - 20px); background:red;">
<div class="innerDiv" style="max-height:100%; position:relative; background:green;">
<textarea style="width:90%; height:100px; color:black; background:#CCC; resize:none; font-size:24px;"></textarea>
<div style="height:10px;"></div>
<span class="button">RESET</span>
<span class="button">SEND</span>


While $(".innerDiv").css('prop', 'value'); would change that property to that value on every $(".innerDiv"), your problem comes in when you use $(".outerDiv").height() and $(".innerDiv").height() as part of that value calculation. There, jQuery uses the first one it finds, and it doesn't refer to the specific innerDiv/outerDiv pair you're trying to target.

For that, you need to use .each():

$(".innerDiv").each(function() {
    $(this).css('top', ($(this).parent().height() - $(this).height()) / 2);