Reputation: 1581
I'm really at a loss here. I have the following code:
function AddHeightToBottom(footerHeight)
{
if ($('#myId1').length)
{
$('#myId1').height($('#myId1').height() + footerHeight);
}
console.log(('#myId2').length);
if ($('#myId2').length > 0)
{
var dHeight = $('#myId1').height();
var aHeight = $('.AF').height();
$('#myId1').height(dHeight + aHeight);
var newHeight = $('#myId1').height();
alert(newHeight);
}
else
{
alert('why?!??????');
}
}
$('#myId2').length is coming out to 1, as I'd expect. However, when it does the comparison
if(1 > 0)
it's doing thing 2 EVERY time and I have no idea why. Any help would be appreciated.
Upvotes: 0
Views: 52
Reputation: 1581
The element I was trying to grab was being loaded in an iFrame, so document.ready() wasn't catching it. I don't know why Firebug was telling me the length was 1 when it was actually 0.
Upvotes: 0
Reputation: 1237
You are using jquery, so make sure you are running it in document.ready:
$( document ).ready(function() {
if($('#element').length > 0) { //do thing 1 }
else { //do thing 2 }
});
If you are calling this in another function, then that function must appear in document.ready. A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. * Quoted from link below.
https://learn.jquery.com/using-jquery-core/document-ready/
function AddHeightToBottom(footerHeight)
{
if ($('#myId1').length){
$('#myId1').height($('#myId1').height() + footerHeight);
}
console.log(('#myId2').length);
if ($('#myId2').length > 0)
{
alert("See, it works...");
var dHeight = $('#myId1').height();
var aHeight = $('.AF').height();
$('#myId1').height(dHeight + aHeight);
var newHeight = $('#myId1').height();
alert("New height: " + newHeight);
}
else
{
alert('why?!??????');
}
}
$( document ).ready(function() {
var footerHeight = 25;
AddHeightToBottom(footerHeight);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myId1">div with id of myId1</div>
<br>
<div id="myId2">div with id of myId2</div>
Upvotes: 5