jQuery - .each() returning only the first element attributes, need to store each element attribute and use in each child element
-
18-09-2019 - |
Question
I'm having headaches trying to make this work: I have a <a> element with a background-image defined with style="" attribute and I have put a function to append inside the <a> element a <span> handling different background-positions for :hover effects with opacity changes. The thing is, I need to get the same style attribute from each <a> element to each child <span> but only the first background-image is copied to all the <span> elements, even using $("span.hover").parent().attr("style") as selector!
http://pastebin.me/ac4cc52af64f6e831366ca61c7bbe63b
Above you can see how it looks like and see that it's not working properly.
Solution
This:
var $ans = $("span.hover").parent().attr("style");
should be
var $ans = $(this).parent().attr("style");
You're re-getting all the spans each time, which gives you the first one.
Tested & working.