- jQuery для начинающих. Часть 4. Селекторы
- Бродим по иерархии объектов в DOM’е
- Фильтры
- Слайды
- Цикл статей
- Selecting Elements
- link Selecting Elements by ID
- link Selecting Elements by Class Name
- link Selecting Elements by Attribute
- link Selecting Elements by Compound CSS Selector
- link Selecting Elements with a Comma-separated List of Selectors
- link Pseudo-Selectors
- link Choosing Selectors
- link Does My Selection Contain Any Elements?
- link Saving Selections
- link Refining & Filtering Selections
- link Selecting Form Elements
- link :checked
- link :disabled
- link :enabled
- link :input
- link :selected
- link Selecting by type
- Last Updated
- Suggestions, Problems, Feedback?
- Chapters
- Books
jQuery для начинающих. Часть 4. Селекторы
Последнее время мне всё чаще задают вопрос как выбрать тот или иной элемент в DOM’е, и данный пост будет сплошь посвящен селекторам в jQuery, возможно большинство из них Вы видели в различных источниках, но собрать их воедино все же стоит…
Во всех примерах используется сокращенный вариант вызова jQuery методов, используя функцию $ (знак доллара)
Селекторы в jQuery базируются на CSS селекторах, а так же поддерживают XPath. Дабы не закапываться в документацию буду приводить примеры, много примеров. Но начнем с самых азов…
Для начала нам понадобиться макет HTML странички (вполне типичный макет):
< div id = "header" >
< h1 > < a href = "/" title = "homepage" >Title < / a > < / h1 >
< h2 >Sub-title < span >small description < / span > < / h2 >
< / div >
< div id = "wrapper" >
< div id = "content" >
< div class = "post" >
< h3 >Post Title < / h3 >
< p >Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed viverra tempus sapien.
Cras condimentum, tellus id lacinia fermentum, tortor lectus tincidunt sapien,
vel varius augue tortor vel tortor. < / p >
< span >Image Title < / span >
< img src = "/image1.jpg" alt = "Image Alt Text" / >
< p >Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed viverra tempus sapien.
Cras condimentum, tellus id lacinia fermentum, tortor lectus tincidunt sapien,
vel varius augue tortor vel tortor. < / p >
< span class = "inner-banner" >Banner Text < / span >
< p >Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed viverra tempus sapien.
Cras condimentum, tellus id lacinia fermentum, tortor lectus tincidunt sapien,
vel varius augue tortor vel tortor. < / p >
< / div >
< span id = "banner" >< img src = "/banner1.jpg" alt = "Big Banner" / > < / span >
< div class = "post" >
< h3 >Post Title < / h3 >
< p >Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed viverra tempus sapien.
Cras condimentum, tellus id lacinia fermentum, tortor lectus tincidunt sapien,
vel varius augue tortor vel tortor. < / p >
< span >Image Title < / span >
< img src = "/image2.jpg" alt = "Image Alt Text" / >
< p >Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed viverra tempus sapien.
Cras condimentum, tellus id lacinia fermentum, tortor lectus tincidunt sapien,
vel varius augue tortor vel tortor. < / p >
< span class = "inner-banner" >Banner Text < / span >
< p >Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed viverra tempus sapien.
Cras condimentum, tellus id lacinia fermentum, tortor lectus tincidunt sapien,
vel varius augue tortor vel tortor. < / p >
< / div >
< / div >
< / div >
< div id = "sidebar" >
< ul >
< li > < a href = "/item0.html" >Menu Item 0 < / a > < / li >
< li > < a href = "/item1.html" >Menu Item 1 < / a > < / li >
< li > < a href = "/item2.html" >Menu Item 2 < / a > < / li >
< li > < a href = "/item3.html" >Menu Item 3 < / a > < / li >
< / ul >
< / div >
< div id = "footer" >
Copyright © 2008
< / div >
А теперь приступим к выборкам:
Выбор элементов по Id либо ClassName аналогично используемому в CSS
$ ( ‘#sidebar’ ) ; // выбор элемента с id = sidebar
$ ( ‘.post’ ) ; // выбор элементов с class = post
$ ( ‘div#sidebar’ ) ; // выбор элемента div с id = sidebar
$ ( ‘div.post’ ) ; // выбор элементов div с class = post
Примечание: используйте валидные имена классов и id
Бродим по иерархии объектов в DOM’е
Аналогичный результат так же можно получить используя следующую конструкцию:
Выбор только непосредственных потомков
$ ( ‘div > span’ ) ; // выбор всех span элементов в элементах div, где span является прямым потомком div’a
Как же лучше поступить, что работает быстрее? Надо бы протестировать…
Так же селекторы можно группировать:
$ ( ‘span + img’ ) ; // выбор всех img элементов перед которыми идут span элементы
$ ( ‘span ~ img’ ) ; // выбор всех img элементов после первого элемента span
$ ( ‘#banner’ ) . prev ( ) ; // выбор предыдущего элемента от найденого
$ ( ‘#banner’ ) . next ( ) ; // выбор следующего элемента от найденого
Выбор всех элементов, всех предков, всех потомков
$ ( ‘*’ ) ; // выбор всех элементов
$ ( ‘p > *’ ) ; // выбор всех потомков элементов p
$ ( ‘p’ ) . children ( ) ; // —
$ ( ‘p’ ) . parent ( ) ; // выбор всех прямых предков элементов p
$ ( ‘* > p’ ) ; // выбор всех предков элементов p (скорей всего Вам не понадобится)
$ ( ‘p’ ) . parents ( ) ; // —
$ ( ‘p’ ) . parents ( ‘div’ ) ; // выбор всех предков элемента p которые есть div (parents принимает в качестве параметра селектор)
Фильтры
$ ( ‘div:first’ ) ; // выбираем первый div в доме
$ ( ‘div:last’ ) ; // выбираем последний div в доме
$ ( ‘div:not(.red)’ ) ; // выбираем div’ы у которых нету класса red
$ ( ‘div:even’ ) ; // выбираем четные div’ы
$ ( ‘div:odd’ ) ; // выбираем нечетные div’ы
$ ( ‘div:eq(N)’ ) ; // выбираем div идущим под номером N в DOMe
$ ( ‘div:gt(N)’ ) ; // выбираем div’ы, индекс которых больше чем N в DOMe
$ ( ‘div:lt(N)’ ) ; // выбираем div’ы, индекс которых меньше чем N в DOMe
$ ( ‘:header’ ) ; // выбо заголовоков h1, h2, h3 и т.д.
$ ( ‘div:animated’ ) ; // выбор элементов с активной анимацией
Фильтры по контенту и видимости:
$ ( ‘div:contains(text)’ ) ; // выбираем div’ы содержащие текст
$ ( ‘div:empty’ ) ; // выбираем пустые div’ы
$ ( ‘div:has(p)’ ) ; // выбираем div’ы которые содержат p
$ ( ‘div.red’ ) . filter ( ‘.bold’ ) // выбираем div’ы которые содержат класс red и класс bold
$ ( ‘div:hidden’ ) ; // выбираем скрытые div’ы
$ ( ‘div:visible’ ) ; // выбираем видимые div’ы
Так же есть фильтры по атрибутам:
$ ( «div[id]» ) ; // выбор всех div с атрибутом id
$ ( «div[title=’my’]» ) ; // выбор всех div с атрибутом title=my
$ ( «div[title!=’my’]» ) ; // выбор всех div с атрибутом title не равного my
$ ( «div[title^=’my’]» ) ; // выбор всех div с атрибутом title начинающихся с my
// ,,
$ ( «div[title$=’my’]» ) ; // выбор всех div с атрибутом title заканчивающихся на my
// ,,
$ ( «div[title*=’my’]» ) ; // выбор всех div с атрибутом title содержащим my
// ,, ,
так же стоит отдельно отметить следующий фильтр:
$ ( «a[rel~=’external’]» ) ; // выбор всех A с атрибутом rel содержащим external в списке значений разделенных пробелом
В результате его работы будут выбраны следующие теги:
Для работы с элементами форм есть ряд селекторов позволяющий выбирать по типу элемента и фильтров — enabled/disabled/selected/checked:
$ ( «:text» ) ; // выбор всех input элементов с типом =text
$ ( «:radio» ) ; // выбор всех input элементов с типом =radio
// и так далее
$ ( «input:enabled» ) ; // выбор всех включенных элементов input
$ ( «input:checked» ) ; // выбор всех отмеченных чекбоксов
Фильтры так же можно группировать:
$ ( «div[name=city]:visible:has(p)» ) ; // выбор видимого div’a с именем city, который содержит тег p
Приведу так же ряд полезных селекторов для работы с элементами форм:
$ ( «form select[name=city] option:selected» ) . val ( ) ; // получение выбранного(-ых) элементов в селекте city
$ ( «form :radio[name=some]:checked» ) . val ( ) ; // получение выбранного значения радиобатона с именем some
$ ( «form :checkbox:checked» ) ; // выбор всех выбранных чекбоксов
Если Вам хочеться опробывать как это все работает — то для этого можете воспользоваться тестовой страничкой
Слайды
Как-то слишком много текста получилось, пожалуй пора показывать слайды 😉
Цикл статей
Selecting Elements
The most basic concept of jQuery is to «select some elements and do something with them.» jQuery supports most CSS3 selectors, as well as some non-standard selectors. For a complete selector reference, visit the Selectors documentation on api.jquery.com.
link Selecting Elements by ID
$( "#myId" ); // Note IDs must be unique per page.
link Selecting Elements by Class Name
link Selecting Elements by Attribute
link Selecting Elements by Compound CSS Selector
link Selecting Elements with a Comma-separated List of Selectors
link Pseudo-Selectors
$( "a.external:first" );
$( "tr:odd" );
// Select all input-like elements in a form (more on this below).
$( "#myForm :input" );
$( "div:visible" );
// All except the first three divs.
$( "div:gt(2)" );
// All currently animated divs.
$( "div:animated" );
Note: When using the :visible and :hidden pseudo-selectors, jQuery tests the actual visibility of the element, not its CSS visibility or display properties. jQuery looks to see if the element’s physical height and width on the page are both greater than zero.
Elements that have not been added to the DOM will always be considered hidden, even if the CSS that would affect them would render them visible. See the Manipulating Elements section to learn how to create and add elements to the DOM.
link Choosing Selectors
Choosing good selectors is one way to improve JavaScript’s performance. Too much specificity can be a bad thing. A selector such as #myTable thead tr th.special is overkill if a selector such as #myTable th.special will get the job done.
link Does My Selection Contain Any Elements?
Once you’ve made a selection, you’ll often want to know whether you have anything to work with. A common mistake is to use:
This won’t work. When a selection is made using $() , an object is always returned, and objects always evaluate to true . Even if the selection doesn’t contain any elements, the code inside the if statement will still run.
The best way to determine if there are any elements is to test the selection’s .length property, which tells you how many elements were selected. If the answer is 0, the .length property will evaluate to false when used as a boolean value:
// Testing whether a selection contains elements.
if ( $( "div.foo" ).length )
.
>
link Saving Selections
jQuery doesn't cache elements for you. If you've made a selection that you might need to make again, you should save the selection in a variable rather than making the selection repeatedly.
Once the selection is stored in a variable, you can call jQuery methods on the variable just like you would have called them on the original selection.
A selection only fetches the elements that are on the page at the time the selection is made. If elements are added to the page later, you'll have to repeat the selection or otherwise add them to the selection stored in the variable. Stored selections don't magically update when the DOM changes.
link Refining & Filtering Selections
Sometimes the selection contains more than what you're after. jQuery offers several methods for refining and filtering selections.
// Refining selections.
$( "div.foo" ).has( "p" ); // div.foo elements that contain
tags
$( "h1" ).not( ".bar" ); // h1 elements that don't have a class of bar
$( "ul li" ).filter( ".current" ); // unordered list items with class of current
$( "ul li" ).first(); // just the first unordered list item
$( "ul li" ).eq( 5 ); // the sixth
link Selecting Form Elements
jQuery offers several pseudo-selectors that help find elements in forms. These are especially helpful because it can be difficult to distinguish between form elements based on their state or type using standard CSS selectors.
link :checked
Not to be confused with :checkbox, :checked targets checked checkboxes, but keep in mind that this selector works also for checked radio buttons, and elements (for elements only, use the :selected selector):
The :checked pseudo-selector works when used with checkboxes, radio buttons and selects.
link :disabled
Using the :disabled pseudo-selector targets any elements with the disabled attribute:
In order to get the best performance using :disabled , first select elements with a standard jQuery selector, then use .filter( ":disabled" ) , or precede the pseudo-selector with a tag name or some other selector.
link :enabled
Basically the inverse of the :disabled pseudo-selector, the :enabled pseudo-selector targets any elements that do not have a disabled attribute:
In order to get the best performance using :enabled , first select elements with a standard jQuery selector, then use .filter( ":enabled" ) , or precede the pseudo-selector with a tag name or some other selector.
link :input
Using the :input selector selects all , , , and elements:
link :selected
Using the :selected pseudo-selector targets any selected items in elements:
In order to get the best performance using :selected , first select elements with a standard jQuery selector, then use .filter( ":selected" ) , or precede the pseudo-selector with a tag name or some other selector.
link Selecting by type
jQuery provides pseudo selectors to select form-specific elements according to their type:
For all of these there are side notes about performance, so be sure to check out the API docs for more in-depth information.
Last Updated
Suggestions, Problems, Feedback?
Chapters
Books
Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath