Document getelementbyid что это
Поиск: getElement*, querySelector*
Свойства навигации по DOM хороши, когда элементы расположены рядом. А что, если нет? Как получить произвольный элемент страницы?
Для этого в DOM есть дополнительные методы поиска.
document.getElementById или просто id
Также есть глобальная переменная с именем, указанным в id :
…Но это только если мы не объявили в JavaScript переменную с таким же именем, иначе она будет иметь приоритет:
Это поведение соответствует стандарту, но поддерживается в основном для совместимости, как осколок далёкого прошлого.
Браузер пытается помочь нам, смешивая пространства имён JS и DOM. Это удобно для простых скриптов, которые находятся прямо в HTML, но, вообще говоря, не очень хорошо. Возможны конфликты имён. Кроме того, при чтении JS-кода, не видя HTML, непонятно, откуда берётся переменная.
В этом учебнике мы будем обращаться к элементам по id в примерах для краткости, когда очевидно, откуда берётся элемент.
querySelectorAll
Этот метод действительно мощный, потому что можно использовать любой CSS-селектор.
querySelector
Метод elem.querySelector(css) возвращает первый элемент, соответствующий данному CSS-селектору.
matches
Предыдущие методы искали по DOM.
Этот метод удобен, когда мы перебираем элементы (например, в массиве или в чём-то подобном) и пытаемся выбрать те из них, которые нас интересуют.
closest
Предки элемента – родитель, родитель родителя, его родитель и так далее. Вместе они образуют цепочку иерархии от элемента до вершины.
Метод elem.closest(css) ищет ближайшего предка, который соответствует CSS-селектору. Сам элемент также включается в поиск.
getElementsBy*
Существуют также другие методы поиска элементов по тегу, классу и так далее.
На данный момент, они скорее исторические, так как querySelector более чем эффективен.
Здесь мы рассмотрим их для полноты картины, также вы можете встретить их в старом коде.
Давайте найдём все input в таблице:
Другая распространённая ошибка – написать:
Попытка присвоить значение коллекции, а не элементам внутри неё, не сработает.
Нужно перебрать коллекцию в цикле или получить элемент по номеру и уже ему присваивать значение, например, так:
Живые коллекции
Все методы «getElementsBy*» возвращают живую коллекцию. Такие коллекции всегда отражают текущее состояние документа и автоматически обновляются при его изменении.
В приведённом ниже примере есть два скрипта.
Напротив, querySelectorAll возвращает статическую коллекцию. Это похоже на фиксированный массив элементов.
Если мы будем использовать его в примере выше, то оба скрипта вернут длину коллекции, равную 1 :
Теперь мы легко видим разницу. Длина статической коллекции не изменилась после появления нового div в документе.
Итого
Есть 6 основных методов поиска элементов в DOM:
Метод | Ищет по. | Ищет внутри элемента? | Возвращает живую коллекцию? |
querySelector | CSS-selector | ✔ | — |
querySelectorAll | CSS-selector | ✔ | — |
getElementById | id | — | — |
getElementsByName | name | — | ✔ |
getElementsByTagName | tag or ‘*’ | ✔ | ✔ |
getElementsByClassName | class | ✔ | ✔ |
И, напоследок, давайте упомянем ещё один метод, который проверяет наличие отношений между предком и потомком:
Задачи
Поиск элементов
Вот документ с таблицей и формой.
Javascript Shorthand for getElementById
Is there any shorthand for the JavaScript document.getElementById? Or is there any way I can define one? It gets repetitive retyping that over and over.
21 Answers 21
To save an extra character you could pollute the String prototype like this:
It works in some browsers and you can access elements this way:
I have chosen the name of the property almost randomly. If you actually wanted to use this shorthand I would suggest coming up with something easier to type.
You can easily create shorthand easily yourself:
A quick alternative to contribute:
There’s a catch, it doesn’t work in browsers that don’t let you extend prototypes (e.g. IE6).
is the same as writing:
I don’t suggest using the former method as it is not common practice.
(Shorthand for not only getting element by ID, but also getting element by class :P)
I use something like
There are several good answers here and several are dancing around jQuery-like syntax, but not one mentions actually using jQuery. If you’re not against trying it, check out jQuery. It let’s you select elements super easy like this..
There’s none built-in.
If you don’t mind polluting the global namespace, why not:
Yes, it gets repetitive to use the same function over and over each time with a different argument:
So a nice thing would be a function that takes all those arguments at the same time:
Then you would have references to all your elements stored in one object:
But you would still have to list all those ids.
You could simplify it even more if you want all elements with ids:
But it would be pretty expensive to call this function if you have many elements.
So, theoretically, if you would use the with keyword you could write code like this:
Well, you could create a shorthand function, that’s what I do.
and then when you wanted to get it, you just do
Also, another useful trick that I found, is that if you want to get the value or innerHTML of an item ID, you can make functions like this:
Hope you like it!
I actually made a kind of mini javascript library based on this whole idea. Here it is.
If this is on your own site, consider using a library like jQuery to give you this and many other useful shorthands that also abstract away browser differences. Personally, if I wrote enough code to be bothered by the longhand, I would include jQuery.
Alright, I’ve dabbled in JavaScript before, but the most useful thing I’ve written is a CSS style-switcher. So I’m somewhat new to this. Let’s say I have HTML code like this:
I know how document.getElementsByClassName and document.getElementById work, but I would like to get more specific. Sorry if this has been asked before.
7 Answers 7
getElementById only returns one node, but getElementsByClassName returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that’s what the [0] is for—it’s just like an array).
You can do it like this:
or, if you want to do it with with less error checking and more brevity, it can be done in one line like this:
Caveats: some older browsers don’t support getElementsByClassName (e.g. older versions of IE). That function can be shimmed into place if missing.
This is where I recommend using a library that has built-in CSS3 selector support rather than worrying about browser compatibility yourself (let someone else do all the work). If you want just a library to do that, then Sizzle will work great. In Sizzle, this would be be done like this:
jQuery has the Sizzle library built-in and in jQuery, this would be: