Reprinted fromYou’ve probably never heard of these 15 HTML element methods!

Let’s start by discussing the differences between HTML and DOM.

Obviously, a normal

element is a piece of HTML code that can be applied to any file with an.html extension. The element comes with a set of attributes that control how it is displayed and behaves.

That’s all there is to the element, which has nothing to do with JavaScript.

What DOM does is associate your JavaScript code with HTML elements in your document, allowing you to interact with those elements as objects.

This is known as the Document Object Model.

Each element in HTML corresponds to a DOM ‘interface’ that defines several properties (properties that are typically mapped to HTML elements) and methods. For example, a

element corresponds to an HTMLTableElement interface.

You can get a reference to an element as follows:

const searchBox = document.getElementById('search-box');
Copy the code

You now have access to all the attributes and methods defined on the element. For example, you can access its value property through searchbox.value, or you can call searchbox.focus () to move the cursor over the input box.

Thanks for taking this 58 second DOM orientation course, lol.

The problem now is that most elements offer no interesting methods. Therefore, unless you go out of your way to search the official documentation specification for things that may never be used, it’s easy to overlook the odd tip.

Fortunately, browsing norms and organizing tips are two of my favorite ways to avoid getting bogged down. So, let’s get started…

If you want to try these tricks and you have some browser DevTools available, you can select an element in the element tree, type $0 in the console, and it will return you a reference to the selected element. If you need to return an object for that element, type dir($0).

In the console, you can implement a rich variety of functions.

1. The table method

The original table element (still the number one website layout method today) itself came with a number of clever ways to create tables that were as simple as building an IKEA table.

Here are some useful tips:

const tableEl = document.querySelector('table');

const headRow = tableEl.createHead().insertRow();
headerRow.insertCell().textContent = 'Make';
headerRow.insertCell().textContent = 'Model';
headerRow.insertCell().textContent = 'Color';

const newRow = tableEl.insertRow();
newRow.insertCell().textContent = 'Yes';
newRow.insertCell().textContent = 'No';
newRow.insertCell().textContent = 'Thank you';
Copy the code

You don’t need the document.createElement() method at all in this code.

If you call.insertrow () directly on a table element, it will even automatically insert a element for you, isn’t that great?

2.scrollIntoView()

You know what? When a page URL contains the #something element, once the page loads, the browser automatically scrolls to the element with that ID.

This is a nice feature, but it doesn’t work if you render elements after the page loads.

However, you can manually reactivate this feature by:

document.querySelector(document.location.hash).scrollIntoView();
Copy the code

3.hidden

Okay, so hidden may not be a method, but if you protest, I’ll argue that there’s probably a setter behind hidden, and that’s a real method, right?

Anyway, have you ever used myelement.style. display = ‘none’ to hide an element? If so, please don’t do it again!

Simply call myElement.Hidden = true to implement element hiding.

4.toggle()

Well, toggle isn’t really an element method either, it’s actually a method on an element attribute. Strictly speaking, this is a kind of elements to add or delete a class method, the practice is myElement classList. Toggle (‘ some – class).

If you’ve ever added a class to an element through an if conditional statement, you should do it now.

The correct way is to pass a second argument to the toggle method, and if it returns true, the specified class is added to the element.

el.classList.toggle('some-orange-class', theme === 'orange');
Copy the code

I know what you’re thinking: it defies the original meaning of the word ‘toggle’, as developers from the IE era have argued, and the second argument should be banished altogether.

So, I take it back. There is no need to insist on this writing method, please feel free!

5.querySelector()

Well, of course you know this method, but my guess is that only 17% of developers know that this method can be used on any element.

For example, myElement.querySelector(‘.my-class’) returns all elements in myElement’s children that contain the my-class class.

6.closest

This method, which can be used on any element, looks up the tree structure of the element and can be thought of as the opposite of querySelector(). Therefore, I can get the corresponding header for the current content by:

myElement.closest('article').querySelector('h1');
Copy the code

This method first goes up to the most recent

element and then down to the most recent

element.

7.getBoundingClientRect()

When you call this method on a DOM element, you return a simple object with details about its spatial structure.

{x: 604.875, y: 1312, width: 701.625, height: 31, right: 1306.5, bottom: 1343, left: 604.875}Copy the code

However, there are two things to note when calling this method:

Calling this method causes elements to be redrawn, which can take milliseconds, depending on the device and the complexity of the page. Therefore, if you need to call this method repeatedly, such as in a scenario that uses animation, you need to pay special attention to this.

Not all browsers return these values. Are they responsible?

8.matches()

Suppose I need to check whether an element contains a particular class.

This is the most complicated way:

if (myElement.className.indexOf('some-class') > -1) {
  // do something
}
Copy the code

A little better than the above, but irrelevant to this article:

Best way:

if (myElement.matches('.some-class')) {
  // do something
}
Copy the code

9.insertAdjacentElement()

I just learned this one today! It acts like appendChild(), but with more control over where to insert child elements.

ParentEl. InsertAdjacentElement (‘ beforeend, newEl) and parentEl. The appendChild (newEl) effect is the same, but beyond that, You can also specify beforeBEGIN, AfterBEGIN, or Afterend values, and elements will be inserted in the positions indicated by their names.

What control!

10.contains()

Have you ever been in a situation where you need to know if an element is contained within another element? At least THAT’s what I often get.

For example, suppose I was processing a mouse click event and needed to know whether it happened inside a modal window or outside (so I could close the window), I would do something like this:

const handleClick = e => { if (! modalEl.contains(e.target)) modalEl.hidden = true; };Copy the code

ModalEl in the code is a reference to the modal window, while E.target represents the various elements where click events occur.

The interesting thing is that every time I have this situation, the first time I write the code, 100 percent of the time I write the logic backwards.

Even though I was vigilant and tried to write the logic upside down before saving the code, I still got it wrong.

11.getAttribute()

This is without a doubt the least useful of all element methods, except for one scenario.

Do you remember that I mentioned at the beginning of this article that an object’s property also maps to its property attributes (I emphasized this in bold, not italics)?

But in one scenario, this assumption is not true. This is the href characteristic of an element, such as cat .

Calling el.href does not return /animals/cat, contrary to what you might have guessed. Because the element implements HTMLHyperlinkElementUtils interface, this interface provides a series of auxiliary attributes, such as prototol and hash, etc., to show the value associated with the target of a link.

Href is one of those useful attributes that returns the full URL, stripped of unwanted whitespace, rather than the relative URL specified in the attribute.

Thus, if you need to retrieve string literals from the href property, you have to use the el.getAttribute(‘href’) method.

12. The three talisman of dialog elements

< Dialog > is a relatively new element that brings with it two half-working methods, and one very nice one. The show() and close() methods work as you might expect, and I think it’s ok.

The showModal() method displays the < Dialog > element at the top of the page, centered and aligned, which is the expected modal window behavior. You don’t need to specify z-Index, or manually add a gray background, or listen for the ESC key to close the window. Browsers understand how modal Windows work and automate the behavior you expect.

13.forEach()

In some cases, when you get a reference to a list of elements, you can use the forEach() method iteratively.

Looping with for() is a 2014 cliche.

Suppose you want to record the urls of all the links on your page, enter the following code as long as you don’t mind seeing errors.

document.getElementsByTagName('a').forEach(el ==> {
  console.log(el.href);
});
Copy the code

You can also do this:

document.querySelectorAll('a').forEach(el ==> {
  console.log(el.href);
});
Copy the code

The problem is that getElementsByTagName and other similar get… The querySelectorAll method returns an HTMLCollection interface, while the querySelectorAll method returns a NodeList interface.

The NodeList interface provides forEach() methods (as well as keys(), values(), and entries()).

Ideally, it would be better for each method to return a simple array rather than some array-like object. But don’t worry, ECMA provides us with the array.from () method, which converts all of these array-like objects into a real Array.

So, code like this should work:

Array.from(document.getElementsByTagName('a')).forEach(el ==> {
  console.log(el.href);
});
Copy the code

Bonus level: Once you’ve created an array, you can use map(), filter(), reduce() and various other array methods on it. For example, regardless of purpose, you can return an array of all external links as follows:

Array.from(document.querySelectorAll('a')) .map(el => el.origin) .filter(origin => origin ! == document.origin) .filter(Boolean);Copy the code

One of my favorite methods is.filter(Boolean), which will definitely cause me a lot of trouble debugging problems in the future, haha.

14. The form

As you probably already know, < form> has a submit() method. But you may not know that forms have a reset() method, and you can also call the reportValidity() method when you need to validate form elements.

Alternatively, you can call a form’s attributes by adding the element’s name attribute to the elements attribute. For example, myformel.elements. Email will return a < input name=”email” /> element belonging to a < form> (‘ belonging ‘does not necessarily mean it is a’ child ‘).

Okay, I was lying to you back there. Elements does not return a list of elements, but a list of controls (which is obviously not an array, since there is no need to do so).

For example: If you have three radio buttons, each with the same name animal, formel.elements. Animal will return a reference to the radio button set (one control, three elements).

While formEl. Elements. The animal. The value will return the value of the selected radio button.

This syntax looks very funny, let us look to break down: formEl is one of the elements, elements are corresponding HTMLFormControlsCollection interface, this is not a true array, each item may not represent an HTML element. Animal is a collection of radio buttons that are grouped together only because they have the same name property (for which the RadioNodeList interface was created), while Value returns the value property of the selected radio button in that collection.

15.select()

I should probably reframe this article so that the last one doesn’t seem too insignificant. In any case, the.select() method selects everything in the element you specify.