1

In jQuery, the css property of an element, can be returned using methods. One example is the width() method that returns the width of an element, like this:

$('div').click(function() {
    alert($(this).width());
});

However, in vanilla JS, I tried the following code, but it returned null:

document.querySelector('div').onclick = function() {
    alert(this.style.width);
}

How can I make it correct? I hope someone could help me with this.

jst16
  • 84
  • 9

3 Answers3

4

Use getComputedStyle to get the width.

Here is a snippet

document.querySelector('div').onclick = function() {
var width = window.getComputedStyle(this,null).getPropertyValue("width");
    alert(width);
}

DEMO

brk
  • 48,835
  • 10
  • 56
  • 78
0

this here points to event object.you can it to the following

window.onload = function() {
  document.querySelector('div').addEventListener('click', function(event) {
    getWidth(event)
  });
}

function getWidth(event) {

  console.log(event.target.style.width);
}
<div style="width:300px">
  hellow
</div>

Hope it helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
0

Similar question has been asked earlier, How to get an HTML element's style values in javascript?. The ans is as below, the answer also includes a sample code snippet to get css using JavaScript.

The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.

Community
  • 1
  • 1
Yogesh
  • 397
  • 3
  • 18