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.

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for sharing your idea
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.