-2

Is there a way to store style attr in a variable using JS ?

I tried this example

<div style="width: 100px; height: 100px; background: cyan"></div>

var style = 'style="' + $("div").attr('style') + '"';
    alert(style);
1
  • 1
    what is it you are trying to achieve, because this gets the style string correctly e.g width: 100px; height: 100px; background: cyan Mar 27, 2016 at 17:15

2 Answers 2

1

Are you trying this on your website exactly as the code appears here? If so, it's probably returning undefined because you have more than one 'div' present on the page. Try giving the div in question an ID, and change the JS from $('div') to $('#whateveridyouchose').

Try this code to rule out the image's availability as an issue:

$(document).ready (function () {
  var style = 'style="' + $("selectorofimage").attr('style') + '"'; alert(style);
});
4
  • It's actually an image, the path to element is good. The problem could be that image is not loaded when script runs.
    – Alex Barbu
    Mar 27, 2016 at 18:40
  • That'd certainly result in undefined, you could wrap the JS in a document.ready function to rule out that possibility. To confirm, the JS above will return the styles that are explicitly assigned to the DOM element in question. With your use-case being an image, I'm wondering if maybe you're trying to get the dimensions of the image itself, rather than the style attrs? Just wanting to confirm that you're barking up the right tree.
    – Donny West
    Mar 27, 2016 at 18:47
  • The style of image contains only positioning and dimensions properties. I wrapped that script in onAvailable() function and it still returns undefined.
    – Alex Barbu
    Mar 27, 2016 at 18:52
  • Edited my answer above, try that code rather than the onAvailable function... assuming the image is in your markup and not being added after page load via AJAX or something. That should return any styles that are set inline on the image itself.
    – Donny West
    Mar 27, 2016 at 18:59
0
var style = 'style="' + document.getElementsByTagName('div')[0].getAttribute('style') + '"';

is the pure JavaScript version of your example.

1
  • If put the JS on my website it will show style="undefined"
    – Alex Barbu
    Mar 27, 2016 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.