I can't really get why the following selector works as expected (i.e. get the td
):
table tr td
but this one doesn't:
table > tr > td
The td
is a descendant of tr
, which in turn is a descendant of table
, but they are also children of each other. Therefore, I thought that the >
selector would work too.
I made two fiddles:
Why isn't the >
selector working here?
The element > element selector selects those elements which are the children of the specific parent. The operand on the left side of > is the parent and the operand on the right is the children element. Example: Match all <p> element that are child of only <div> element.
Descendant Selector :The descendant Selector selects all child elements of the selected parent element. In this example, the descendant selector selects all li of selected ul elements. 2. Direct Child Selector : This selector selects only the direct child of the selected element.
A child selector is made up of two or more selectors separated by ">". It matches a P element that is a descendant of an LI; the LI element must be the child of an OL element; the OL element must be a descendant of a DIV.
tr:nth-child(even) or tr:nth-child(2n) Represents the even rows of an HTML table: 2, 4, 6, etc. :nth-child(7) Represents the seventh element.
In HTML, browsers implicitly add a tbody
element within which to contain the tr
elements1, so in reality, tr
is never a child of table
.
Consequently, you have to do this instead:
table > tbody > tr > td
Of course, if you add a tbody
element yourself, you use the same selector. The spec explains when a tbody
is added implicitly otherwise:
Tag omission
A
tbody
element's start tag may be omitted if the first thing inside thetbody
element is atr
element, and if the element is not immediately preceded by atbody thead
, ortfoot
element whose end tag has been omitted.
1This is not the case for XHTML documents that are properly served as application/xhtml+xml
, however, given its XML roots.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With