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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With