-1

I have a dom element like this.

<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;">
    <div class="loading-indicator">loading...</div>
</div>

I want to take a width from tag div which is 228 and store in some variable which I can use later.

var st = 228px; // dynamically

Here I wanted to use.

var secondDiv = document.createElement('div');
secondDiv.style = "background-color:#2C8DC2;color:white;padding:5px; margin-top:102px;height: 50px; width : st; border-style: solid;"; 

Now What I am trying here is :

var abc = firstDiv.getAttribute('style');

I am getting : "width: 228px; overflow: auto; height: 100px;"

abc.width;

But this is coming undefined.

How to fetch that value.

Alfonso Tienda
  • 3,442
  • 1
  • 19
  • 34
David
  • 4,266
  • 8
  • 34
  • 69
  • The [*style* property](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) is an object, not a string. – RobG Jul 21 '17 at 07:13
  • @RobG exactly, but it is coming as a string. – David Jul 21 '17 at 07:14
  • Yes,it is supposed to come as `string`. That's how they've designed it. – Aakash Verma Jul 21 '17 at 07:29
  • @David—when you use *getAttribute*, you get the value of the HTML attribute, which in many cases is different to the related property. The value returned by the ***style* property** is an **object**, it is a totally different value to the **string** returned by `getAttribute('style')`. See [*Does CSS code initialize .style properties of DOM objects?*](https://stackoverflow.com/questions/39234483/does-css-code-initialize-style-properties-of-dom-objects) – RobG Jul 22 '17 at 00:09

3 Answers3

0

You could try like this.

window.getComputedStyle(ele); gives you element style. 

var ele = document.getElementById("123"), // Do not use #
    eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;
console.log(eleWidth);
<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;">
    <div class="loading-indicator">loading...</div>
</div>
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

In jQuery, you can do

alert($("#123").css("width")); // which will return 228px;

<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;">
    <div class="loading-indicator">loading...</div>
</div>

if you still want to achieve it in straight javascript

use this reference : How to get an HTML element's style values in javascript?

Arun pandian M
  • 862
  • 10
  • 17
-1

Why wouldn't you use jQuery?

console.log($(`#123`).css('width'));
<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>
  
<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;">
    <div class="loading-indicator">loading...</div>
</div>
Aakash Verma
  • 3,705
  • 5
  • 29
  • 66