I am trying out the following code:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("span").click(function(){
alert($(this).offsetParent().length);
});
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p><span>Click me away!</span></p>
<p>Click me too!</p>
</body>
</html>
From the jQuery documentation, offsetParent() is supposed to return the closest positioned parent, positioned meaning one with position defined explicitly as ‘static,absoluteorrelative`. here, none is declared for any element, yet the alert pops up 1. How come?
First, let as look at the return result:
So for
$(span).offsetParent()you get theHTMLelement.Now let’s look at the implementation of
offsetParent:From the code above we see that if we don’t have positioned parent
offsetParentreturns theHTMLelement.The only bad things is that when I looked at the documentation that wasn’t there.
To check whether there’s actually an
offsetParentyou can use:document.getElementsByTagName('html')[0] === $(elem).offsetParent()[0]