Am I doing something wrong? It looks like this only works in IE, though I can't see what I'm expecting that others can't handle.
<div id="test" style="height:4em;overflow:scroll;">
one<br />two<br />three<br />four<br />five<br />six<br />seven<br />eight<br />nine<br />ten<br />
<b id="item1">I should e into view!</b>
</div>
<script><!--
document.getElementById("item1").offsetParent.scrollTop=1000;
//--></script>
(please don't answer why don't you use "test", because this is a simplified example to demonstrate I have an issue using offsetParent
)
Am I doing something wrong? It looks like this only works in IE, though I can't see what I'm expecting that others can't handle.
<div id="test" style="height:4em;overflow:scroll;">
one<br />two<br />three<br />four<br />five<br />six<br />seven<br />eight<br />nine<br />ten<br />
<b id="item1">I should e into view!</b>
</div>
<script><!--
document.getElementById("item1").offsetParent.scrollTop=1000;
//--></script>
(please don't answer why don't you use "test", because this is a simplified example to demonstrate I have an issue using offsetParent
)
2 Answers
Reset to default 6Just reading the documentation on offsetParent and looking at what happens in Chrome and Firefox, it's pretty clear that offsetParent
is being set to the <body>
element and your div with id="test"
is not positioned.
If you add position: relative
to your container div, it will pick up that as the offsetParent and work properly. I don't know if this the fix you are looking for, but it works.
The alternative, of course, is using .parentElement
instead of offsetParent
, depending on your use-case.
use document.getElementById("item1").parentElement.scrollTop = 1000
offset parent is not meant to find the parent element of a node rather the
"nearest table cell or root element" which in your case is the <body>
tag.
See the MDN Doc for offsetParent