How can I access the attributes of an element by using JS?

How can I access the attributes of an element by using JS? I tried (example) element.style.width. I only need the numeric value, I mean 50 instead 50px.

Upvotes: 0

Views: 67

Answers (3)

Lex
Lex

Reputation: 3

In this way...

let theD = document.getElementById('theDiv');
theD.innerHTML = theD.offsetWidth;
#theDiv {
  width: 50px;
  height: 50px;
  background-color: coral;
}
<div id="theDiv"></div>

Upvotes: 0

Mike Ezzati
Mike Ezzati

Reputation: 3166

Use window.getComputedStyle(element).width

Upvotes: 1

Shanon Jackson
Shanon Jackson

Reputation: 6531

element.offsetWidth will give you the width as a numeric value.

Alternatively you could use element.style.width and parse it into a number with

Number.parseInt("50px")

or the faster bitwise version

~~("50px".replace("px", ""))

Upvotes: 1

Related Questions