Adam Halasz
Adam Halasz

Reputation: 58291

Javascript : Get Parent Node Name

How should I get the Parent nodeName of a text while I'm on it with the cursor?

<div id="holder" contentEditable="true">
    Stackoverflow is the <b>coolest</b> Q&A website in the world.
</div>

And as a result we have:

So if the cursor is on the coolest I would like to get it's parent nodeName which is b

Please no libraries, just pure javascript.

Upvotes: 2

Views: 2719

Answers (2)

mVChr
mVChr

Reputation: 50167

if (document.addEventListener) {
    document.getElementById('holder').addEventListener('mouseover', function (e) {
        somevar = e.target.nodeName;
    }, false);
} else {
    document.getElementById('holder').attachEvent('onmouseover', function (e) {
        somevar = e.srcElement.nodeName;
    });
}

EDIT: updated code and example in accordance with question edit and comments.

See example.

Upvotes: 7

Daniel Szabo
Daniel Szabo

Reputation: 7281

<div id="holder" contentEditable="true">
   Stackoverflow is the <b onclick="alert(this.tagName)">coolest</b> Q&A website in the world.
</div>

Upvotes: 1

Related Questions