Get Width of <a> Element in Pixels

Hello all,

I’m trying to get the width of a <a> element.
I’ve found solutions on the internet like.

var test = document.getElementById("bla").style.pixelWidt;
var test = document.getElementById("bla").offsetWidth;
var test = document.getElementById("bla").clientWidth;

But none of these seems to work properly for my <a> elements.

Any ideas?


Use offsetWidth.

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <title>Get link width</title>
    <a href="#">Some link text</a>
    <a href="#">Some more link text</a>
      var links = document.querySelectorAll("a");
      for (var i=0; i<links.length; i++){
        var width = links[i].offsetWidth;
        console.log("Link " + (i + 1) + " has a width of " + width + "px.");

I need the pixel length to set the size of an inputbox and place it over the link for the user to adjust it.
I tried already the solution you provided (see previous message) but the input box just isn’t the same size as the <a> element.

I just tried the following and that seems to work:
I find the number of characters of the link and then set the width of the inpubox like follows:

document.getElementById('tex').style.width = test * 9.2 + "px";

The 9.2 depends on the font size offcourse

Thank you for your help!

I’m curious.

Could you possibly post enough HTML/JS that I can recreate what you are doing. Or a link, if that’s possible.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.