2

can you please explain, how can i get the correct path of styles of html element that has been added through css (eg, background:ulr()) using javascript or jQuery.

var img = document.querySelectorAll('*');
img.forEach(function(i){
   var imageSrc = new Image(); 
     i.addEventListener("mouseover", function(e){

      if(i.style.background){

        }
    })
});

can the i.style.background find the correct css DOM path? i've added a fiddle. https://codepen.io/saifudazzlings/pen/VQvooy

1
  • "can the i.style.background find the correct css DOM path" Sorry, not clear what you are asking. Commented Feb 2, 2018 at 7:08

1 Answer 1

3

HTMLElement.style will only give you the result of the inline styles of an element. If you need to get the styles that have been computed from an external stylesheet, you need to use Window.getComputedStyle:

var bgImage = window.getComputedStyle(i).backgroundImage;

See the updated codepen here using Window.getComputedStyle. The background image URL is printed when you hover over the div with the background.

Sign up to request clarification or add additional context in comments.

2 Comments

but, if i want to edit a css property, i should use the correct DOM path, for eg: for <div class="a">, in my css i've selected that with the parent element like .parent .a{color:#000000;}. when i am using javascript to edit that property how can i get that correct path like $('.parent a'). @christian santos
To use JS to edit the property, you don't need to get the exact selector, you can use the DOM element directly to edit the styles (you can also pass this DOM element to jQuery by calling $(element) -- see this codepen for an example of modifying the bgImage on hover: codepen.io/anon/pen/wyMeZe

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.