4

i have this kind of HTML:

<g>
    <path d="..." />
    <text class="abbr"></text>
</g>

and jQuery code:

$("text.abbr").mouseover(function () {
    $(this).closest("path").prev().attr("class", "active");
});

I know, SVG has a lot of limitations. Please, help me to select closest previous element path (if i hover element text) using jQuery or JavaScript to add a class to element path.

Thanks in advance!

max
  • 612
  • 7
  • 26

2 Answers2

2

.closest traverses the tree up, i.e. to the parent. You seem to simply want the previous sibling:

$(this).prev()
// or if you want to select the previous only if it is a path:
$(this).prev('path');

If the element you are looking for is not an immediate sibling, i.e. there are other elements in between, have a look at jquery find closest previous sibling with class , using the tag name instead of a class.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Another way using cloeset

 $(this).closest("g").find('path').attr("class", "active"); 
Samir Das
  • 1,878
  • 12
  • 20
  • Note that this will select **all** `path` elements inside `g`, not only the previous siblings. – Felix Kling May 25 '15 at 16:32
  • Yes you are right but `query selector ` inside `find()` can be used to find more precisely. Your answer is better. I have just tried to fix his mistake – Samir Das May 25 '15 at 16:34