Javascript gets external parent div id

I have a structure that looks like below, I'm trying to get id foo. This is only DIV with an identifier if we exit onclick func(), which means that there will not be other DIVs containing the identifier inside foo. However, inside there foomay be other tags that contain an identifier (for example, bye, hello).

No framework is used.

<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(event)">1</td></tr>
            <tr><td onclick="func(event)">2</td></tr>
        </table>
    </div>
</div>
+3
source share
6 answers

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>
+3
source
function findIdOfParent(obj) {
  var o = obj;
  while(!o.id) {
    o = o.parentNode;
  }

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

findIdOfParent DOM node. onclick="findIdOfParent(this);", event, , DOM node event.target , .

+8

parentNode , , DOM.

..:

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

elem - ,

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

? , onclick , div (s), this:

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

http://jsfiddle.net/fRxYB/

?

+1

, :

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/

0
source

Source: https://habr.com/ru/post/1784756/


All Articles