javascript obtain outer parent id DIV

给你一囗甜甜゛ 提交于 2019-12-05 20:18:27

This should do it:

<div id="bar"></div>
<div id="foo">
    <p><p>
    <div class="bye">
        <input id="bye" type="text" value="test" />
        <input id="hello" type="text" value="test" />
        <table>
            <tr><td onclick="func(this)">1</td></tr>
            <tr><td onclick="func(this)">2</td></tr>
        </table>
    </div>
</div>

<script type="text/javascript">
    function func(elt) {
            // Traverse up until root hit or DIV with ID found
        while (elt && (elt.tagName != "DIV" || !elt.id))
            elt = elt.parentNode;
        if (elt) // Check we found a DIV with an ID
            alert(elt.id);
    }
</script>
function findIdOfParent(obj) {
  var o = obj;
  while(!o.id) {
    o = o.parentNode;
  }

  alert(o.id); // 'foo'
}

The function findIdOfParent takes a DOM node. You could call it with onclick="findIdOfParent(this);", but if you only want to pass event, as in your example, you'd have to extract the DOM node from event.target or whatever you're currently doing.

You could use the parentNode property of the clicked element to iterate up through the DOM tree.

ie:

<td onclick="func(this)">
function func(item)
{
   var parent = item.parentNode;
   // and so on, or something similar
   var divId = div.id;
}

elem is the element that call the function on click

var found = false;
var myId = "";
while (elem &&!found) { 
    if (elem.id){
        found = true; 
        myId = elem.id;
    }
    elem = elem.parentNode; 
} 

Can't you apply a simpler pattern? Instead of having onclick properties in your cells, attach a single click handler to your outermost div(s), then you just need to refer to this:

document.getElementById("foo").onclick = function(event) {
    if(e.target.tagName.toLowerCase() == "td") {
        alert(this.id);
    }
};

http://jsfiddle.net/fRxYB/

Or am I completely missing the point?

To have a somewhat more generic version, I'd suggest this:

function func(event) {
    var par = findTop(event.target);
    console.log(par);
};

function findTop(node) {
    while(node.parentNode && node.parentNode.nodeName !== 'BODY') {
        node = node.parentNode;
    }

    return node;
}

example: http://www.jsfiddle.net/4yUqL/37/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!