Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't table > tr > td work when using the child selector?

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:

  1. Child: http://jsfiddle.net/brLee/
  2. Descendant: http://jsfiddle.net/brLee/1/

Why isn't the > selector working here?

like image 546
pimvdb Avatar asked Apr 06 '11 15:04

pimvdb


People also ask

Which is the correct way to select child element?

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.

What's the difference between child selector and descendant selector?

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.

Which character is used in a child selector?

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.

What is TR nth child?

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.


1 Answers

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 the tbody element is a tr element, and if the element is not immediately preceded by a tbody thead, or tfoot 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.

like image 54
BoltClock Avatar answered Sep 16 '22 11:09

BoltClock