I need to check whether a parent is a tbody or thead tag.
I have this right now, which does not work:
item.parent("thead")[0] = "<thead>" ? console.log("yes") : console.log("no");
Doesn't work though.
Any hints what I'm doing wrong?
Thanks!
I need to check whether a parent is a tbody or thead tag.
I have this right now, which does not work:
item.parent("thead")[0] = "<thead>" ? console.log("yes") : console.log("no");
Doesn't work though.
Any hints what I'm doing wrong?
Thanks!
Share Improve this question asked Jan 4, 2012 at 20:57 frequentfrequent 28.5k61 gold badges187 silver badges336 bronze badges 1-
can you clarify whether you are looking for the direct parent or just checking to see if the
item
is contained within thethead
ortbody
? – Evan Davis Commented Jan 4, 2012 at 21:20
5 Answers
Reset to default 8Think this will work:
console.log(item.parent("thead").is("thead") ? "Yes" : "No");
http://jsfiddle/G9LJT/0/ - No
http://jsfiddle/G9LJT/1/ - Yes
...
item.parent("thead")[0]
refers to the first DOM element of your selector.
You can use .is
as follows:
var isthead = item.parent().is("thead") ? "yes" : "no";
Note that .is
returns true
if any of the elements in the set matches, so you need .first
to only test on the first element.
You are paring a DOM element to a string. You just need to check if the parent is what you want it to be by trying to select and checking the length:
item.parent('thead').length ? console.log('YES') : console.log('NO');
You can select a anscestor thead
tag and check it's length
property to see if it exists:
item.parents("thead:first").length > 0 ? console.log("yes") : console.log("no");
Here is a demo: http://jsfiddle/upxyB/
Notice that I used the :first
pseudo-selector to only get the first match since parents()
is capable of returning a set of results (for instance if you have nested tables).
On a side-note, item.parent("thead")[0] = "<thead>"
will always return true, you need double equals signs for a parison operator: item.parent("thead")[0] == "<thead>"
Docs for parison operators - https://developer.mozilla/en/JavaScript/Reference/Operators/Comparison_Operators
Try:
var item = $("#something");
if (item.parent().get(0).tagName.toLowerCase() === 'thead')
alert('parent is thead');
else
alert('parent is not thead');
It should work with ie6+, ff, chrome/safari.