HTML and CSS Reference
In-Depth Information
If we want to select all the td elements in a document, we can use the following:
> $('td')
This will return an array of 9 elements.
The second core way we can select elements is based on one of their attributes. If we wish
to select all the elements with a placeholder attribute, the following selection can be used:
> $('[placeholder]')
Notice the use of [] brackets around the attribute name. This will find all elements with a
placeholder attribute, regardless of its value.
Additionally, we may wish to specify that the element has an attribute with a specific value,
in which case the following syntax can be used:
> $'[datetime="2013-10-14"]')
In this case we are mixing single and double quotes, since we wish to express the value as
a string inside the string that is the selection criteria.
Selecting elements based on attributes becomes even more useful due to the fact it is pos-
sible to add your own custom attributes to HTML elements. Adding custom attributes to
elements allows you to associate data with an element, and then use this data in any way
we need.
For instance, we may want to denote that a cell in a table represents the name of a task;
therefore we could add the following attribute to the element:
<td data-name-field="true">
In order to quickly find all name field nodes, we could then execute the following selection:
> $('[data-name-field]')
Alternatively, we may wish to associate a priority with tasks, so each tr element could in-
clude the following:
<tr data-priority="high">
or
<tr data-priority="medium">
We can then select all the high priority rows in the table with the following selection:
> $('[data-priority="high"]')
We will see below that the prefix added to this attribute (“data-“) is more than a convention,
and allows for other possibilities. Binding data directly to elements turns out to be an
enormously powerful concept. It provides a way to add context to elements in a manner
Search WWH ::




Custom Search