- 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
- .find()
- Добавлен в версии: 1.0 .find( selector )
- Добавлен в версии: 1.6 .find( element )
- jQuery: Find Element With Data Attribute
- Find a Data Attribute Using jQuery .find() Method
- Find a Data Attribute Using a CSS Attribute Selector
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
.find()
Описание: Поиск потомков внутри каждого элемента в текущем наборе соотвествующих элементов с фильтрацией по селектору, объекту jQuery или элементу.
Добавлен в версии: 1.0 .find( selector )
Добавлен в версии: 1.6 .find( element )
Учитывая что объект jQuery представляет из себя набор DOM элементов, метод .find() разрешает нам находить потомки элементов в DOM дереве и конструировать новый объект jQuery из найденных элементов. Методы .find() и .children() похожи, за исключением того, что последний проходит вниз по DOM дереву только на один уровень.
Первая сигнатура метода .find() принимает выражение селектора того же типа что и функция $() . Элементы будут фильтроваться путем проверки - соответстует ли данный элементы селектору.
Рассмотрим страницу на которой расположены вложенные списки:
ul class="level-1">
li class="item-i">I li>
li class="item-ii">II
ul class="level-2">
li class="item-a">A li>
li class="item-b">B
ul class="level-3">
li class="item-1">1 li>
li class="item-2">2 li>
li class="item-3">3 li>
ul>
li>
li class="item-c">C li>
ul>
li>
li class="item-iii">III li>
ul>
Если мы начнем с пункта II, мы можем найти элементы списка внутри него:
$( "li.item-ii" ).find( "li" ).css( "background-color", "red" );
Результатом работы этого кода станет красный фон для элементов A, B, 1, 2, 3 и C. Даже если элемент II соответствует выражению селектора, он не включается в результаты, так как только потомки считаются кандидатами на соответствие.
В отличие от большинства методов обхода, метод .find() требует обязательного выражения селектора. Если нам нужны все потомки, то мы можем указать универсальный селектор '*' для этого.
Контекст селектора реализованн в методе .find() , следовательно, $( "li.item-ii" ).find( "li" ) эквивалентно $( "li", "li.item-ii" ) .
Начиная с jQuery 1.6, вы также можете фильтровать выбор при помощи переданного объекта jQuery или элемента. С тем же списком описанным выше, если мы начнем с:
И затем передадим этот jQuery объект в find:
$( "li.item-ii" ).find( allListElements );
То это вернет jQuery коллекцию, которая содержит который содержит только элементы списка, являющиеся потомками элемента II.
Аналогично, фильтровать можно по элементу:
var item1 = $( "li.item-1" )[ 0 ];
$( "li.item-ii" ).find( item1 ).css( "background-color", "red" );
Результатом этого вызова будет красный фон у элемента 1.
- Ajax
- Глобальные Ajax события
- Вспомогательные методы
- Низкоуровневый интерфейс
- Сокращенные методы
- Базовые
- Пользовательские
- Затухание
- Скольжение
- События браузера
- Загрузка документа
- Прикрепление обработчиков
- Объект событие
- События формы
- События клавиатуры
- События мыши
- Class атрибут
- Копирование
- DOM Вставка вокруг
- DOM Вставка внутрь
- DOM Вставка вне
- DOM Удаление
- DOM Замена
- Общие аттрибуты
- Свойства стилей
- Манипуляция коллекциями
- Хранилище данных
- DOM методы элементов
- Методы установки
- Экземпляр объекта jQuery
- Глобальный объект jQuery
- Атрибут
- Базовые
- Базовые фильтры
- Фильтры потомков
- Фильтры содержимого
- Форма
- Иерархия
- jQuery расширение
- Фильтр видимости
- Фильтрация
- Обход
- Обход элементов
- Версия 1.3
- Версия 1.7
- Версия 1.8
- Версия 1.9
- Версия 1.10
- Версия 3.0
Русская документация по jQuery.
При использовании любых материалов с сайта ссылка на сайт обязательна.jQuery: Find Element With Data Attribute
- Find a Data Attribute Using jQuery .find() Method
- Find a Data Attribute Using a CSS Attribute Selector
- Find a Data Attribute Using the .filter() Method
To search for an element with a data attribute using jQuery, you can use the .find() method, the .filter() method, or a CSS attribute selector. This article teaches you how you can use them all using practical code examples.
Find a Data Attribute Using jQuery .find() Method
In jQuery, the .find() method allows you to search for an element on a web page using a CSS selector. Here, you can use it to find a data attribute if you write the right CSS selector.
From this, you can do what you want with elements that match the CSS selector. In the example below, we searched for data-name=Edison and changed its font size to 3em .
html lang="en"> head> meta charset="utf-8"> title>01-jQuery-find-data-attrtitle> script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer">script> head> body> main> ul> li data-name="Edison">Thomas Edisonli> li data-name="Einstein">Albert Einsteinli> li data-name="Rutherford">Ernest Rutherfordli> ul> main> script> $(document).ready(function() $("ul").find("[data-name='Edison']").css('font-size', '3em'); >); script> body> html>
Find a Data Attribute Using a CSS Attribute Selector
You can find a data attribute using a CSS attribute selector. But there are two ways to do this, depending on your HTML markup.
In the first example below, the list items have data attributes. So, you can use a CSS descendant selector, which consists of a tag selector and a CSS attribute selector.