Поиск: getElement*, querySelector*
Свойства навигации по DOM хороши, когда элементы расположены рядом. А что, если нет? Как получить произвольный элемент страницы?
Для этого в DOM есть дополнительные методы поиска.
document.getElementById или просто id
Если у элемента есть атрибут id , то мы можем получить его вызовом document.getElementById(id) , где бы он ни находился.
Также есть глобальная переменная с именем, указанным в id :
…Но это только если мы не объявили в JavaScript переменную с таким же именем, иначе она будет иметь приоритет:
Это поведение соответствует стандарту, но поддерживается в основном для совместимости, как осколок далёкого прошлого.
Браузер пытается помочь нам, смешивая пространства имён JS и DOM. Это удобно для простых скриптов, которые находятся прямо в HTML, но, вообще говоря, не очень хорошо. Возможны конфликты имён. Кроме того, при чтении JS-кода, не видя HTML, непонятно, откуда берётся переменная.
В этом учебнике мы будем обращаться к элементам по id в примерах для краткости, когда очевидно, откуда берётся элемент.
В реальной жизни лучше использовать document.getElementById .
Значение id должно быть уникальным. В документе может быть только один элемент с данным id .
Если в документе есть несколько элементов с одинаковым значением id , то поведение методов поиска непредсказуемо. Браузер может вернуть любой из них случайным образом. Поэтому, пожалуйста, придерживайтесь правила сохранения уникальности id .
Метод getElementById можно вызвать только для объекта document . Он осуществляет поиск по id по всему документу.
querySelectorAll
Самый универсальный метод поиска – это elem.querySelectorAll(css) , он возвращает все элементы внутри elem , удовлетворяющие данному CSS-селектору.
Следующий запрос получает все элементы <li> , которые являются последними потомками в <ul> :
Этот метод действительно мощный, потому что можно использовать любой CSS-селектор.
Псевдоклассы в CSS-селекторе, в частности :hover и :active , также поддерживаются. Например, document.querySelectorAll(‘:hover’) вернёт коллекцию (в порядке вложенности: от внешнего к внутреннему) из текущих элементов под курсором мыши.
querySelector
Метод elem.querySelector(css) возвращает первый элемент, соответствующий данному CSS-селектору.
Иначе говоря, результат такой же, как при вызове elem.querySelectorAll(css)[0] , но он сначала найдёт все элементы, а потом возьмёт первый, в то время как elem.querySelector найдёт только первый и остановится. Это быстрее, кроме того, его короче писать.
matches
Предыдущие методы искали по DOM.
Метод elem.matches(css) ничего не ищет, а проверяет, удовлетворяет ли elem CSS-селектору, и возвращает true или false .
Этот метод удобен, когда мы перебираем элементы (например, в массиве или в чём-то подобном) и пытаемся выбрать те из них, которые нас интересуют.
closest
Предки элемента – родитель, родитель родителя, его родитель и так далее. Вместе они образуют цепочку иерархии от элемента до вершины.
Метод elem.closest(css) ищет ближайшего предка, который соответствует CSS-селектору. Сам элемент также включается в поиск.
Другими словами, метод closest поднимается вверх от элемента и проверяет каждого из родителей. Если он соответствует селектору, поиск прекращается. Метод возвращает либо предка, либо null , если такой элемент не найден.
getElementsBy*
Существуют также другие методы поиска элементов по тегу, классу и так далее.
На данный момент, они скорее исторические, так как querySelector более чем эффективен.
Здесь мы рассмотрим их для полноты картины, также вы можете встретить их в старом коде.
- elem.getElementsByTagName(tag) ищет элементы с данным тегом и возвращает их коллекцию. Передав "*" вместо тега, можно получить всех потомков.
- elem.getElementsByClassName(className) возвращает элементы, которые имеют данный CSS-класс.
- document.getElementsByName(name) возвращает элементы с заданным атрибутом name . Очень редко используется.
Давайте найдём все input в таблице:
Одна из самых частых ошибок начинающих разработчиков (впрочем, иногда и не только) – это забыть букву "s" . То есть пробовать вызывать метод getElementByTagName вместо getElementsByTagName .
Буква "s" отсутствует в названии метода getElementById , так как в данном случае возвращает один элемент. Но getElementsByTagName вернёт список элементов, поэтому "s" обязательна.
Другая распространённая ошибка – написать:
Попытка присвоить значение коллекции, а не элементам внутри неё, не сработает.
Нужно перебрать коллекцию в цикле или получить элемент по номеру и уже ему присваивать значение, например, так:
Ищем элементы с классом .article :
Живые коллекции
Все методы "getElementsBy*" возвращают живую коллекцию. Такие коллекции всегда отражают текущее состояние документа и автоматически обновляются при его изменении.
В приведённом ниже примере есть два скрипта.
- Первый создаёт ссылку на коллекцию <div> . На этот момент её длина равна 1 .
- Второй скрипт запускается после того, как браузер встречает ещё один <div> , теперь её длина – 2 .
Напротив, querySelectorAll возвращает статическую коллекцию. Это похоже на фиксированный массив элементов.
Если мы будем использовать его в примере выше, то оба скрипта вернут длину коллекции, равную 1 :
Теперь мы легко видим разницу. Длина статической коллекции не изменилась после появления нового div в документе.
Итого
Есть 6 основных методов поиска элементов в DOM:
Метод | Ищет по. | Ищет внутри элемента? | Возвращает живую коллекцию? |
querySelector | CSS-selector | ✔ | — |
querySelectorAll | CSS-selector | ✔ | — |
getElementById | id | — | — |
getElementsByName | name | — | ✔ |
getElementsByTagName | tag or ‘*’ | ✔ | ✔ |
getElementsByClassName | class | ✔ | ✔ |
Безусловно, наиболее часто используемыми в настоящее время являются методы querySelector и querySelectorAll , но и методы getElement(s)By* могут быть полезны в отдельных случаях, а также встречаются в старом коде.
- Есть метод elem.matches(css) , который проверяет, удовлетворяет ли элемент CSS-селектору.
- Метод elem.closest(css) ищет ближайшего по иерархии предка, соответствующему данному CSS-селектору. Сам элемент также включён в поиск.
И, напоследок, давайте упомянем ещё один метод, который проверяет наличие отношений между предком и потомком:
Element.id
Свойство id представляет идентификатор элемента, отражая глобальный атрибут id.
Если значение id не пустое, то оно должно быть уникально в документе.
id часто используется с getElementById , чтобы получить нужный элемент. Часто применяют ID как селектор, для стилизации документа, с помощью CSS.
Примечание: идентификаторы чувствительны к регистру, но вам следует избегать создание id, которых различает регистр (смотрите Чувствительность к регистру в классах и идентификаторов).
How can I get an element's ID value with JavaScript?
Yes you can just use the .id property of the dom element, for example:
Or, something like this:
Yes you can simply say:
This would work too:
(If element where the 1st paragraph in your document)
Super Easy Way is
Tell me if this helps
In events handler you can get id as follows
This gets and alerts the id of the element with the id «ele».
You need to check if is a string to avoid getting a child element
Yes. You can get an element by its ID by calling document.getElementById . It will return an element node if found, and null otherwise:
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.13.43310
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Searching: getElement*, querySelector*
DOM navigation properties are great when elements are close to each other. What if they are not? How to get an arbitrary element of the page?
There are additional searching methods for that.
document.getElementById or just id
If an element has the id attribute, we can get the element using the method document.getElementById(id) , no matter where it is.
Also, there’s a global variable named by id that references the element:
…That’s unless we declare a JavaScript variable with the same name, then it takes precedence:
This behavior is described in the specification, but it is supported mainly for compatibility.
The browser tries to help us by mixing namespaces of JS and DOM. That’s fine for simple scripts, inlined into HTML, but generally isn’t a good thing. There may be naming conflicts. Also, when one reads JS code and doesn’t have HTML in view, it’s not obvious where the variable comes from.
Here in the tutorial we use id to directly reference an element for brevity, when it’s obvious where the element comes from.
In real life document.getElementById is the preferred method.
The id must be unique. There can be only one element in the document with the given id .
If there are multiple elements with the same id , then the behavior of methods that use it is unpredictable, e.g. document.getElementById may return any of such elements at random. So please stick to the rule and keep id unique.
The method getElementById can be called only on document object. It looks for the given id in the whole document.
querySelectorAll
By far, the most versatile method, elem.querySelectorAll(css) returns all elements inside elem matching the given CSS selector.
Here we look for all <li> elements that are last children:
This method is indeed powerful, because any CSS selector can be used.
Pseudo-classes in the CSS selector like :hover and :active are also supported. For instance, document.querySelectorAll(‘:hover’) will return the collection with elements that the pointer is over now (in nesting order: from the outermost <html> to the most nested one).
querySelector
The call to elem.querySelector(css) returns the first element for the given CSS selector.
In other words, the result is the same as elem.querySelectorAll(css)[0] , but the latter is looking for all elements and picking one, while elem.querySelector just looks for one. So it’s faster and also shorter to write.
matches
Previous methods were searching the DOM.
The elem.matches(css) does not look for anything, it merely checks if elem matches the given CSS-selector. It returns true or false .
The method comes in handy when we are iterating over elements (like in an array or something) and trying to filter out those that interest us.
closest
Ancestors of an element are: parent, the parent of parent, its parent and so on. The ancestors together form the chain of parents from the element to the top.
The method elem.closest(css) looks for the nearest ancestor that matches the CSS-selector. The elem itself is also included in the search.
In other words, the method closest goes up from the element and checks each of parents. If it matches the selector, then the search stops, and the ancestor is returned.
getElementsBy*
There are also other methods to look for nodes by a tag, class, etc.
Today, they are mostly history, as querySelector is more powerful and shorter to write.
So here we cover them mainly for completeness, while you can still find them in the old scripts.
- elem.getElementsByTagName(tag) looks for elements with the given tag and returns the collection of them. The tag parameter can also be a star "*" for “any tags”.
- elem.getElementsByClassName(className) returns elements that have the given CSS class.
- document.getElementsByName(name) returns elements with the given name attribute, document-wide. Very rarely used.
Let’s find all input tags inside the table:
Novice developers sometimes forget the letter "s" . That is, they try to call getElementByTagName instead of getElementsByTagName .
The "s" letter is absent in getElementById , because it returns a single element. But getElementsByTagName returns a collection of elements, so there’s "s" inside.
Another widespread novice mistake is to write:
That won’t work, because it takes a collection of inputs and assigns the value to it rather than to elements inside it.
We should either iterate over the collection or get an element by its index, and then assign, like this:
Looking for .article elements:
Live collections
All methods "getElementsBy*" return a live collection. Such collections always reflect the current state of the document and “auto-update” when it changes.
In the example below, there are two scripts.
- The first one creates a reference to the collection of <div> . As of now, its length is 1 .
- The second scripts runs after the browser meets one more <div> , so its length is 2 .
In contrast, querySelectorAll returns a static collection. It’s like a fixed array of elements.
If we use it instead, then both scripts output 1 :
Now we can easily see the difference. The static collection did not increase after the appearance of a new div in the document.
Summary
There are 6 main methods to search for nodes in DOM:
Method | Searches by. | Can call on an element? | Live? |
querySelector | CSS-selector | ✔ | — |
querySelectorAll | CSS-selector | ✔ | — |
getElementById | id | — | — |
getElementsByName | name | — | ✔ |
getElementsByTagName | tag or ‘*’ | ✔ | ✔ |
getElementsByClassName | class | ✔ | ✔ |
By far the most used are querySelector and querySelectorAll , but getElement(s)By* can be sporadically helpful or found in the old scripts.
- There is elem.matches(css) to check if elem matches the given CSS selector.
- There is elem.closest(css) to look for the nearest ancestor that matches the given CSS-selector. The elem itself is also checked.
And let’s mention one more method here to check for the child-parent relationship, as it’s sometimes useful: