Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today we’ll review all the DOM methods for finding elements on a page.

directory

  • GetElementById () – Find elements by ID
  • GetElementsByName () – Finds elements by the name attribute on the tag
  • GetElementsByTagName () – Finds elements by tag name
  • GetElementsByClassName () – Finds elements by their class
  • QuerySelector () – Finds elements using CSS selectors
  • QuerySelectorAll () – same as above

getElementById()

This is probably the most common method of looking up elements by their ID

<div id="root"></div>
Copy the code

We usually define a unique ID for an element in HTML. If the ID is repeated, subsequent elements will not be found.

ID is case sensitive, root and root are different ids.

Use the getElementById(ID) method to get the element

let element = document.getElementById('root');
Copy the code

An Element object is returned if it is found, or null if it does not exist.

GetElementById () example

The HTML structure is as follows

<html>
  <head>
    <title>JavaScript getElementById()</title>
  </head>
  <body>
    <p id="message">hello world</p>
  </body>
</html>
Copy the code

The HTML has a

element with the ID message

const p = document.getElementById('message');
console.log(p);

/ / output:
// <p id="message">hello world</p>
Copy the code

When we find an element, we can style it, manipulate its attributes, look up its parent, child, and so on.

conclusion

  • getElementById()Returns a DOM element, or null if not found.
  • If multiple elements have the same ID, getElementById() returns the first element encountered.

getElementsByName()

Every element in HTML can have a name attribute

<input type="radio" name="language" value="JavaScript">
Copy the code

Unlike ID, multiple HTML attributes can have the same name attribute

<input type="radio" name="language" value="JavaScript">
<input type="radio" name="language" value="TypeScript">
Copy the code
let elements = document.getElementsByName('language');
Copy the code

GetElementsByName () takes the element’s name attribute and returns an element NodeList.

GetElementsByName () example

<! DOCTYPEhtml>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript getElementsByName Demo</title>
</head>
<body>
  <p>Please rate this service:</p>
  <p>
    <input type="radio" name="rate" value="Very satisfied.">Very satisfied with<input type="radio" name="rate" value="Satisfied">Satisfied with the<input type="radio" name="rate" value="General">general<input type="radio" name="rate" value="Dissatisfied">Not satisfied with<input type="radio" name="rate" value="Very dissatisfied.">Very dissatisfied</p>
  <p>
    <button id="btnRate">submit</button>
  </p>
  <script>
    let btn = document.getElementById('btnRate');

    btn.addEventListener('click'.() = > {
      let rates = document.getElementsByName('rate');
      rates.forEach((rate) = > {
        if (rate.checked) {
          alert('Your choice:${rate.value}`); }})});</script>
</body>
</html>
Copy the code

conclusion

  • getElementsByName()Returns the group of elements specified by nameNodeList.
  • NodeListIs the type of a class array, not a real array.

getElementsByTagName()

The getElementsByTagName() method takes a tag name and returns an HTMLCollection, an array-like object, in the order they appear in the document.

<div>
	<p>1</p>
	<p>2</p>
	<p>3</p>
</div>
Copy the code
let elements = document.getElementsByTagName('div');
Copy the code

getElementsByTagName()example

The following example shows the use of getElementsByTagName() to get the number of H2 tags in the HTML, which pops up when we click the Calculate H2 number button.

<! DOCTYPEhtml>
<html>
<head>
  <title>JavaScript getElementsByTagName()</title>
</head>
<body>
  <h1>JavaScript getElementsByTagName()</h1>
  
  <h2>The first heading</h2>
  <p>The first paragraph</p>
  <h2>Second heading</h2>
  <p>Second paragraph</p>
  <h2>The third heading</h2>
  <p>Third paragraph</p>

  <button id="btnCount">Calculate H2 quantity</button>

  <script>
    let btn = document.getElementById('btnCount');
    btn.addEventListener('click'.() = > {
      let headings = document.getElementsByTagName('h2');
      alert(H2 label quantity is:${headings.length}`);
    });
  </script>
</body>
</html>
Copy the code

conclusion

  • getElementsByTagName()Takes a tag name, returns an array of matched elements,

getElementsByClassName()

In HTML, almost every element has a class attribute, because we use it to define styles

<button class="btn btn-primary">save</button>
Copy the code
.btn {
  background-color: red;
}
Copy the code

The getElementsByClassName() method takes a parameter, which can be a string containing one or more class names

let elements = document.getElementsByClassName(classNames)
Copy the code

Such as this

let btn = document.getElementsByClassName('btn');
Copy the code

If there are multiple

let btn = document.getElementsByClassName('btn bt-primary');
Copy the code

Note that we cannot use CSS notation like.btn or.btn-primary.

GetElementsByClassName () also returns an HTMLCollection element, an array-like object.

GetElementsByClassName () example

<div id="app">
  <header>
    <nav>
      <ul id="menu">
        <li class="item">HTML</li>
        <li class="item">CSS</li>
        <li class="item highlight">JavaScript</li>
        <li class="item">TypeScript</li>
      </ul>
    </nav>
    <h1>getElementsByClassName Demo</h1>
  </header>
  <section>
    <article>
      <h2 class="heading-secondary">Example 1</h2>
    </article>
    <article>
      <h2 class="heading-secondary">Example 2</h2>
    </article>
  </section>
</div>
Copy the code

1) Called on the element

Next we get the menu element with getElementById(), and then all elements under the menu element whose class is Item

let menu = document.getElementById('menu');
let items = menu.getElementsByClassName('item');

let data = [].map.call(items, item= > item.textContent);

console.log(data);

/ / output:
// ["HTML", "CSS", "JavaScript", "TypeScript"]
Copy the code

2) Called at the root element

Let’s look at all elements whose class is heading-secondary

let elements = document.getElementsByClassName('heading-secondary');

let data = [].map.call(elements, elem= > elem.textContent);

console.log(data);

/ / output:
// ["Example 1", "Example 2"]
Copy the code

QuerySelector () and querySelectorAll ()

QuerySelector () is a method of the Element interface.

The querySelector() method uses CSS selectors to find the first matched element in the document.

let element = document.querySelector(selector);
Copy the code

SyntaxError is raised if the selector is not a valid CSS syntax.

Returns NULL if no matching element is found.

In addition to using querySelector(), we can also use the querySelectorAll() method to find elements that match a set of CSS selectors.

let elementList = document.querySelectorAll(selector);
Copy the code

If no element is found, an empty NodeList is returned. A NodeList is an array-like object that we can traverse using forEach() or convert to an Array using array.from.

let nodeList = Array.from(document.querySelectorAll(selector));
Copy the code

Basic use case

<! DOCTYPEhtml>
<html>
<head>
  <title>querySelector() Demo</title>
</head>
<body>
  
  <header>
    <div id="logo">
      <img src="img/logo.jpg" alt="Logo" id="logo">
    </div>
    <nav class="primary-nav">
      <ul>
        <li class="menu-item current"><a href="#home">Home page</a></li>
        <li class="menu-item"><a href="#services">service</a></li>
        <li class="menu-item"><a href="#about">about</a></li>
        <li class="menu-item"><a href="#contact">contact</a></li>
      </ul>
    </nav>
  </header>
  <main>
    <h1>Welcome to my class</h1>
    
    <div class="container">
      <section class="section-a">
        <h2>How often do you hear about UI/UX designers, but have no idea what UI/UX is and what the difference is in the work project? This article gives you a quick start on UI, UX, and 9 ways to improve your conversion rate with UX design on your website.</h2>
        <p></p>
        <button>To read more</button>
      </section>
      <section class="section-b">
        <h2>Web Front-end development</h2>
        <p>What positions are available for Web front-end development? What positions are there in the web front end? You've all sort of heard that the pay on the WEB front end is pretty good. But this is just a general statement, in fact, there are many different positions in the WEB front-end, now come with me to learn</p>
        <button>To read more</button>
      </section>
      <section class="section-c">
        <h2>Blockchain development</h2>
        <p>Understand what is blockchain, the system master the technical knowledge required at the bottom of blockchain, the system master the technical knowledge required at the application layer of blockchain, find a 15K+ blockchain development work</p>
        <button>To read more</button>
      </section>
    </div>
  </main>

</body>
</html>
Copy the code

1) Universal selector

* represents a generic selector that matches all elements of any type:

*
Copy the code

Find all elements in the document

let elements = document.querySelectorAll(The '*');
Copy the code

2) Label selector

The following code looks for the first H1 element in the document

let firstH1 = document.querySelector('h1');
Copy the code

Find all the h2 elements

let h2List = document.querySelectorAll('h2');
Copy the code

3) Class selector

Find the first element in HTML whose class is.menu-item

let note = document.querySelector('.menu-item');
Copy the code

Find all elements in HTML whose class is.menu-item

let notes = document.querySelectorAll('.menu-item');
Copy the code

4) ID selector

Find the element whose ID is LOGO

let logo = document.querySelector('#logo');
Copy the code

ID is the only value in the page, so you can’t query it using querySelectorAll().

5) Property selector

Here is some syntax for property selectors

[attribute]
[attribute=value]
[attribute~=value]
[attribute|=value]
[attribute^=value]
[attribute$=value]
[attribute*$*=value]
Copy the code

The following code queries the first element with an autoplay attribute

let autoplay = document.querySelector('[autoplay]');
Copy the code

The following code queries all elements with an autoplay attribute

let autoplays = document.querySelectorAll('[autoplay]');
Copy the code

Packet selector

Find all

and

elements below:

let elements = document.querySelectorAll('div, p');
Copy the code

Combinatorial selector

1) Descendant selector

Find all elements within all p elements

let links = document.querySelector('p a');
Copy the code

2) Child selector

Find all direct li child elements within

    :
let listItems = document.querySelectorAll('ul > li');
Copy the code

Find all li children of ul with class.nav

let listItems = document.querySelectorAll('ul.nav > li');
Copy the code

3) Sibling selector

P ~ a will match all elements after p elements within the same parent element

let links = document.querySelectorAll('p ~ a');
Copy the code

4) Adjacent sibling selectors

H1 + a matches all elements immediately following h1

let links = document.querySelectorAll('h1 + a');
Copy the code

Pseudo class selector

For example, a:visited matches all elements that have already been visited

let visitedLinks = document.querySelectorAll('a:visited');
Copy the code

conclusion

  • querySelector()Finds the first element that matches the CSS selector.
  • querySelectorAll()Find all elements that match the CSS selector.

The last

With querySelector() and querySelectorAll(), there’s no need for any other methods, so if you don’t consider compatibility with IE678, go ahead and use them.

I’m going to stop here today, and I’m going to review tomorrow if I look for parent elements, child elements, and siblings.

If you want to review DOM knowledge with me, wechat search [Xiaoshuai’s programming notes], updated every day