Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

get offsetTop on SVG element

Why is offsetTop returning undefined on this SVG element?

var svg = document.querySelector('svg')
var h1 = document.querySelector('h1')

console.log('svg', svg.offsetTop)
console.log('h1', h1.offsetTop)
<svg width="26" height="30" viewBox="0 0 12 14">
  <path d="M6 4.038L12 0v3.623L6 8 0 3.623V0l6 4.038zm0 6L12 6v3.623L6 14 0 9.623V6l6 4.038z"/>
</svg>
    
<h1>This works</h1>

Upvotes: 8

Views: 4341

Answers (1)

Robert Longson
Robert Longson

Reputation: 124324

The inheritance tree for DOM elements has Element as a base class with SVGElement and HTMLElement deriving separately from that. offsetTop is defined on the HTMLElement interface and not on the Element interface so SVG elements don't support it.

You could get this information by calling element.getBoundingClientRect() instead. This would work for all elements.

Upvotes: 12

Related Questions