0

I'm trying to find out if an element is a child of a table and if so do not run script.

I was thinking something like this

jQuery(jQuery('li:has-parent(table)')) {
    // do this
} 
else {
    // do this
}

But the above doesn't work, any help would be great.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Lee
  • 48
  • 1
  • 5

5 Answers5

5
if (!$(element).parents('table').length){
   // if parent is not table
} else {
   // parent is table
}

"element" is your element selector.

maximkou
  • 5,252
  • 1
  • 20
  • 41
3
if ( $(element).parent('table').length ) { /* parent is table */ }
if ( $(element).closest('table').length ) { /* parent/N-parent is table */ }

jQuery(function($) {
    var $element = $(selector),
        // You can use .closest if you are not looking for a direct parent.
        // http://api.jquery.com/closest/
        isChildOfTable = $element.parent('table').length;

    if ( isChildOfTable ) {

    } 
});

Just to add a .parents vs .closest discussion.

The problem with the jsperf is that it's trying to fetch the element rater then checking the length property. And the result is there fore not concluded in the tests:

enter image description here

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
2
var parentTag = $(element).parent().get(0).tagName;

Check if parentTag equals table or not

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Note that `.tagName` most likely returns in UPPERCASE. https://developer.mozilla.org/en-US/docs/Web/API/element.tagName – Andreas Louv Jun 03 '13 at 11:51
0
if($("#child").is("table > #child")){

}
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
Rich Wandell
  • 123
  • 1
  • 6
0
if($('li').parent('table').length)
A. Wolff
  • 74,033
  • 9
  • 94
  • 155