Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to loop through the style attributes of a div with javascript or jquery?

As the title says I am wondering if it is possible to loop through the style attributes of a div with javascript or jquery. What I want to do is loop through the styles and create an object containing these style names and values.

Here is an example of what I am trying to do:

alert($('#mydiv').attr('style'));

Gives the following:

background-color: #CCCCCC; border-width: 2px; border-style: solid; width: 250px;

And I want to create a object which looks like this:

{"background-color":"#CCCCCC","border-width":"2px","border-style":"solid","width":"250px"}

What I can't figure out is whether this is achievable by looping through the styles or whether I will have to create the object myself using code similar to below:

var style = {};

style['width'] = $('#mydiv').css('width');

Any input of this would be appreciated.

like image 234
Rob Taylor Avatar asked Apr 01 '11 06:04

Rob Taylor


2 Answers

Version 1, using inline style

const style = $("#myDiv").attr("style");
const parts = style.split(";") 
console.log(parts)

let obj = {}
parts.forEach(part => {
  if (part.length > 0) { // skip the empty element after the last ;
    const [key,val] = part.split(':');
    obj[key] = val.trim();
  }  
})

console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="myDiv" style="background-color: #CCCCCC; border-width: 2px; border-style: solid; width: 250px;">My div</div>

Version 2 using computed style of a list of elements

// more code needed to handle rgba
const rgbToHex = rgb => '#' + (rgb.match(/[0-9|.]+/g).map((x, i) => i === 3 ? parseInt(255 * parseFloat(x)).toString(16) : parseInt(x).toString(16)).join('')).padStart(2, '0').toUpperCase();


let obj = {}
const style = window.getComputedStyle(document.getElementById('myDiv')); // 
["background-color", "border-width", "border-style", "width"]
.forEach(rule => {
  const val = style.getPropertyValue(rule)
  obj[rule] = val.includes('rgb') ? rgbToHex(val) : val;
})

console.log(obj)
#myDiv {
  background-color: #CCCCCC;
  border-width: 2px;
  border-style: solid;
  width: 250px;
}
<div id="myDiv">My div</div>
like image 157
mplungjan Avatar answered Oct 26 '22 23:10

mplungjan


For <div id="id" style="color: red"/>, $('#id').attr('style') will return a string color: red so i guess, you can't loop them directly.

However you can create an array string.split(';') and loop over them.

But CSS associated with in inside <style> tag or some css file, i don't think you can get it. However, I am not sure.

like image 23
Santosh Linkha Avatar answered Oct 27 '22 01:10

Santosh Linkha