Akbar Basha
Akbar Basha

Reputation: 1198

How can I find current element text on mouseover using jquery

This is my code,

<!DOCTYPE html>
<html>
<body>

<svg id="a" height="210" width="400">
  <path id="b" d="M150 0 L75 200 L225 200 Z" />
</svg>

</body>
</html>

When mouse is over from b, I want to that code (path id="b" d="M150 0 L75 200 L225 200 Z" ).How can I get it using jquery?

Upvotes: 0

Views: 348

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

You can use outerHTML:

var path = $("#b")[0].outerHTML; // <path id="b" d="M150 0 L75 200 L225 200 Z"></path>

Then combine that with hover:

$("#b").hover(function() {
    console.log($(this)[0].outerHTML);
});

Working Example

As pointed out, this won't work in IE because it doesn't follow specification. You can workaround this by cloning the <path> element, appending it to the HTML body to make it part of the DOM, then grabbing the rendered HTML from there.
Note: This won't be an exact representation of the HTML because it's out of context. For example, it contains the xmlns, but since it's a jQuery object you can modify it how you like:

$("#b").hover(function() {
    // Create a clone of the <path>
    var clone = $(this).clone();
    // Append it to the <body>
    clone.appendTo("body");
    // Wrap it in a containing <div> ... you'll see why in a minute
    clone.wrap("<div>");
    // Now we grab the innerHTML of that containing <div> - outerHTML won't work
    console.log(clone.parent().html());
    // Prints: <path xmlns="http://www.w3.org/2000/svg" id="b" d="M 150 0 L 75 200 L 225 200 Z" /> 

    // Now remove our temporary element again...
    clone.parent().remove();
});

Upvotes: 5

Related Questions