Q . How to get the parentOffset Node(element) of any element.

Brad Johnson. asked, Oct 02 ' 2018

I have the below 2 HTML code and I want to get the node of the parent offset of both the input field.

1st code:

<html>
	<body>
		<div class="als-cont" style="position: absolute; left:30px">
			<input type="text" name="search" id="search" autocomplete="off"/>
		</div>
	</body>
</html>

2nd code :

<html>
	<body>
		<div class="als-cont">
			<input type="text" name="search" id="search" autocomplete="off"/>
		</div>
	</body>
</html>

 

  • JavaScript
  • HTML
  • parentOffset
  • html-element

2 Answers

For this you have to traverse offsetParent to the top of the DOM. You can break it to just first find to get the first offsetParent like below.

function getOffsetParent()
{
	var elem = document.getElementById('search');
	
	while (elem = elem.offsetParent) {
		break;
	}
	return elem;
}

For 1st code you will get the node of <div class="als-cont" style="position: absolute; left:30px">

And For 2nd code you will get the node of <body>

You can traverse the offsetParent up to the top level of the DOM.

function getOffsetLeft( elem )
{
    var offsetLeft = 0;
    do {
      if ( !isNaN( elem.offsetLeft ) )
      {
          offsetLeft += elem.offsetLeft;
      }
    } while( elem = elem.offsetParent );
    return offsetLeft;
}

 

Leave a Ansewer