Home > OS >  How to get the offsetLeft/offsetTop of the <g id="iqaluit"> and <circle id="
How to get the offsetLeft/offsetTop of the <g id="iqaluit"> and <circle id="

Time:10-13

How to get offsetLeft/offsetTop of **<g id="iqaluit"> and <circle id="circle"> elements in javascript. I tried this: but it gives an error TypeError: bar is null.

JS

let bar = document.getElementById('iqaluit');
console.log(bar.offsetLeft, bar.offsetTop)
let circle = document.getElementById('circle');
console.log(circle.offsetLeft, circle.offsetTop);

HTML

<div >
    <canvas  width="500" height="488"> </canvas>
    <svg id="MAP" data-name="MAP" data-province="MAP" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1100 1072.93">
        <g id="City_Labels_Canada" data-name="City Labels Canada">

            <g id="iqaluit" data-name="Iqaluit" data-province="nunavut" >

                <circle id="circle" cx="839.32" cy="390.34" r="3.1"></circle>

                <text x="847" y="394" data-name="Iqaluit" >Iqaluit</text>
            </g>
        </g>
    </svg>
</div>

CodePudding user response:

@Dio, you're on the right track. The svg elements do not support the properties you are looking for but you can access the elements, just a little differently from how you attempted, with the document. See below.

Also, the suggestion from @Syed Qasim Ahmed provides an object, but I'm not sure what you're trying to achieve with offsetLeft/offsetTop, so I can't say if it's equivalent or not.

const map = document.getElementById('MAP');
const bar = map?.querySelector('#iqaluit');

/**
 * You can see the available
 * methods and properties
 * with a for in loop
 */
 
if (bar) {
  for (let i in bar) {
    console.log('what is i?', i);
    console.log('what is bar[i]?', bar[i]);
  }

  const getBoundingClientRect = bar.getBoundingClientRect();

  console.log({ getBoundingClientRect });
}
<div >
    <canvas  width="500" height="488"> </canvas>
    <svg id="MAP" data-name="MAP" data-province="MAP" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1100 1072.93">
        <g id="City_Labels_Canada" data-name="City Labels Canada">

            <g id="iqaluit" data-name="Iqaluit" data-province="nunavut" >

                <circle id="circle" cx="839.32" cy="390.34" r="3.1"></circle>

                <text x="847" y="394" data-name="Iqaluit" >Iqaluit</text>
            </g>
        </g>
    </svg>
</div>

  • Related