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!
Think this will work:
console.log(item.parent("thead").is("thead") ? "Yes" : "No");
http://jsfiddle.net/G9LJT/0/ - No
http://jsfiddle.net/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 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.net/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 comparison operator: item.parent("thead")[0] == "<thead>"
Docs for comparison operators - https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
You are comparing 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');
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.