Find parent node in DOM

Every HTML element in DOM has reference to its parent node. With simple iteration it’s possible to traverse up to requested element. If this loop is wrapped within a function, you will get a very useful code.

/**
 * Function returns reference of named parent element
 * @param {String} tagName Tag name of requested parent element
 * @param {HTMLElement} el Initial element (from which search begins)
 * @return {HTMLElement} Returns reference of found parent element
 */
function findParent (tagName, el) {
    // loop up until parent element is found
    while (el && el.nodeName !== tagName) {
        el = el.parentNode;
    }
    // return found element
    return el;
};

DOM hierarchically is organized like a tree and every element has defined parent node. So, with this function is very easy to find a TABLE for any TD (table cell) element. Here is how:

// search for a TABLE HTML element (from table cell reference)
var tbl = findParent('TABLE', cell);

Instead of HTML reference as start element, function can be modified to accept element ID. In that case, you will have to use document.getElementById() method before loop starts.

Leave a Comment