Javascript:获取父节点名称

时间:2011-02-03 21:26:12

标签: javascript text range parent

当我用光标在文本上时,如何获取文本的父nodeName?

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

结果我们得到了:

  • Stackoverflow是最酷 Q&amp; A 世界网站。

因此,如果光标在coolest上,我想得到它的父节点名b

请不要图书馆,只需要纯粹的javascript。

2 个答案:

答案 0 :(得分:7)

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;
    });
}

编辑:根据问题编辑和评论更新代码和示例。

See example.

答案 1 :(得分:1)

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