Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Table Parent of an Element

Tags:

javascript

I created dynamically a div with a class x in a table. How can I with JavaScript catch the table parent of this div and give it a certain class?

Passing through the tr and td parent Node didn't worked. Any ideas?

like image 520
hassan sleh Avatar asked Dec 10 '22 03:12

hassan sleh


1 Answers

Assuming that no libraries are involved.

function getNearestTableAncestor(htmlElementNode) {
    while (htmlElementNode) {
        htmlElementNode = htmlElementNode.parentNode;
        if (htmlElementNode.tagName.toLowerCase() === 'table') {
            return htmlElementNode;
        }
    }
    return undefined;
}

var table = getNearestTableAncestor(node);
if (table) {
    table.className += ' certain';
}
like image 161
Quentin Avatar answered Jan 04 '23 02:01

Quentin