1

I want to get the computed style of the current element using JS, I am able to fetch the other attributes but am stuck at when it come to css.

here is my code , please help

 document.addEventListener("click", function (e) {
 e.preventDefault();
 var dom_id = e.target.id.toString();

 var dom_class = e.target.className.toString();
 var dom_el = e.target.toString();
 var dom_html = e.target.innerHTML;


  document.getElementById('ospy_id').value = dom_id;
  document.getElementById('ospy_class').value = dom_class;
  document.getElementById('ospy_el').value = dom_el;
           }, 
    false);
CleanX
  • 1,158
  • 3
  • 17
  • 25
  • 7
    Have you checked here https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle – elclanrs Dec 05 '13 at 08:45
  • @elclanrs I am developing a chrome plugin , which gives the attributes of the current element . – CleanX Dec 05 '13 at 09:08
  • @CleanX: Then your question is incorrect. You've specifically asked for the *computed* style, but accepted an answer that gives you only the styles assigned on the element, not from stylesheets. – T.J. Crowder Aug 11 '14 at 07:56

3 Answers3

2

Use following statement to get css of any element

document.getElementById(elementid).style.property

example:
document.getElementById("ospy_class").style.color
sumit
  • 332
  • 2
  • 7
  • It won't give you **computed** styles, if element has `margin: var(--margin-s)`, then `Element.style.margin` will be "var(--margin-s)" (not e.g. "8px") – Daniel Kucal Mar 22 '23 at 16:26
0

If you're using jquery (based on tags you're) you can do something along the lines of:

  $("#elementID").css("color"); 

etc...... Documentation

Last1Here
  • 1,099
  • 2
  • 10
  • 21
  • I am getting the attributes of the target element. So i will not have the class ID as such – CleanX Dec 05 '13 at 09:06
  • Which element are you trying to get the css of ? dom_id ? If so it would be `$("#" + dom_id).css("color");` and so on for other elements – Last1Here Dec 05 '13 at 09:11
0

It's not jQuery but, in Firefox, Opera and Safari you can use window.getComputedStyle(element) to get the computed styles for an element and in IE you can use element.currentStyle. The returned objects are different in each case, and I'm not sure how well either work with elements and styles created using Javascript, but perhaps they'll be useful.

please refer below url...

jQuery CSS plugin that returns computed style of element to pseudo clone that element?

Community
  • 1
  • 1
Sathish RG
  • 112
  • 6