Javascript selecting element by id

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.

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 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.

Читайте также:  Javascript replace text in var

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.
// get all divs in the document let divs = document.getElementsByTagName('div');

Let’s find all input tags inside the table:

 
Your age:
let inputs = table.getElementsByTagName('input'); for (let input of inputs)

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:

// doesn't work document.getElementsByTagName('input').value = 5;

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:

// should work (if there's an input) document.getElementsByTagName('input')[0].value = 5;

Looking for .article elements:

 
Long article

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.

  1. The first one creates a reference to the collection of . As of now, its length is 1 .
  2. The second scripts runs after the browser meets one more , so its length is 2 .
First div
Second div

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 :

First div
Second div

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
Читайте также:  Python pandas open csv

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:

  • elemA.contains(elemB) returns true if elemB is inside elemA (a descendant of elemA ) or when elemA==elemB .

Tasks

Search for elements

Here’s the document with the table and form.

  1. The table with id=»age-table» .
  2. All label elements inside that table (there should be 3 of them).
  3. The first td in that table (with the word “Age”).
  4. The form with name=»search» .
  5. The first input in that form.
  6. The last input in that form.

Open the page table.html in a separate window and make use of browser tools for that.

There are many ways to do it.

// 1. The table with `id="age-table"`. let table = document.getElementById('age-table') // 2. All label elements inside that table table.getElementsByTagName('label') // or document.querySelectorAll('#age-table label') // 3. The first td in that table (with the word "Age") table.rows[0].cells[0] // or table.getElementsByTagName('td')[0] // or table.querySelector('td') // 4. The form with the name "search" // assuming there's only one element with name="search" in the document let form = document.getElementsByName('search')[0] // or, form specifically document.querySelector('form[name="search"]') // 5. The first input in that form. form.getElementsByTagName('input')[0] // or form.querySelector('input') // 6. The last input in that form let inputs = form.querySelectorAll('input') // find all inputs inputs[inputs.length-1] // take the last one

Comments

  • If you have suggestions what to improve — please submit a GitHub issue or a pull request instead of commenting.
  • If you can’t understand something in the article – please elaborate.
  • To insert few words of code, use the tag, for several lines – wrap them in tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)

Источник

Document: getElementById() method

The getElementById() method of the Document interface returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

If you need to get access to an element which doesn’t have an ID, you can use querySelector() to find the element using any selector.

Note: IDs should be unique inside a document. If two or more elements in a document have the same ID, this method returns the first element found.

Syntax

Note: The capitalization of «Id» in the name of this method must be correct for the code to function; getElementByID() is not valid and will not work, however natural it may seem.

Parameters

The ID of the element to locate. The ID is a case-sensitive string which is unique within the document; only one element should have any given ID.

Читайте также:  Cmd python main python

Return value

An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.

Examples

HTML

html lang="en"> head> title>getElementById exampletitle> head> body> p id="para">Some text herep> button onclick="changeColor('blue');">bluebutton> button onclick="changeColor('red');">redbutton> body> html> 

JavaScript

function changeColor(newColor)  const elem = document.getElementById("para"); elem.style.color = newColor; > 

Result

Usage notes

Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll() , getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for «local» versions of the function.

Example

doctype html> html lang="en-US"> head> meta charset="UTF-8" /> title>Documenttitle> head> body> div id="parent-id"> p>hello word1p> p id="test1">hello word2p> p>hello word3p> p>hello word4p> div> script> const parentDOM = document.getElementById("parent-id"); const test1 = parentDOM.getElementById("test1"); // throw error // Uncaught TypeError: parentDOM.getElementById is not a function script> body> html> 

If there is no element with the given id , this function returns null . Note that the id parameter is case-sensitive, so document.getElementById(«Main») will return null instead of the element because «M» and «m» are different for the purposes of this method.

Elements not in the document are not searched by getElementById() . When creating an element and assigning it an ID, you have to insert the element into the document tree with Node.insertBefore() or a similar method before you can access it with getElementById() :

const element = document.createElement("div"); element.id = "testqq"; const el = document.getElementById("testqq"); // el will be null! 

In non-HTML documents, the DOM implementation must have information on which attributes are of type ID. Attributes with the name «id» are not of type ID unless so defined in the document’s DTD. The id attribute is defined to be of ID type in the common cases of XHTML, XUL, and others. Implementations that do not know whether attributes are of type ID or not are expected to return null .

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Document reference for other methods and properties you can use to get references to elements in the document.
  • Document.querySelector() for selectors via queries like ‘div.myclass’
  • xml:id — has a utility method for allowing getElementById() to obtain ‘xml:id’ in XML documents (such as returned by Ajax calls)

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью