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 the requested element. If this loop is wrapped within a function, you will get a very useful code.

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

DOM is hierarchically organized like a tree and every element has defined a 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 = find_parent('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.

Hope this JavaScript lines will be helpful for you.

Leave a Comment