15 obscure properties and methods of DOM objects

When developing modern web sites, JavaScript is heavily used to work with the DOM. Scripts allow you to display and hide the elements from which pages are built, to customize the properties of these elements. DOM objects that interact with from programs have properties and methods. According to the author of the material, the translation of which we publish today, some of them are known to almost all web programmers. But some of which he wants to talk about here are much less famous.



HTML and DOM


First, let's talk about the difference between HTML code and DOM. For example, the usual <table< element is obviously HTML code. This element can be used in html-files, it has a set of attributes that determines the appearance and behavior of the table created with its help. In fact, the <table> tag itself has nothing to do with JavaScript. The link between the HTML elements present in the document and the JavaScript code is provided by the DOM (Document Object Model, Document Object Model). DOM allows you to interact with HTML elements from JavaScript code as if they were objects.

All HTML elements have their own “DOM interfaces”, which define properties (they are usually associated with attributes of HTML elements) and methods. For example, the <table> element has an interface called HTMLTableElement .

You can get a link to an element, for example, using the following construction:

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

After the link to the element is obtained, the programmer has access to the properties and methods that similar elements have. For example, it is possible to work with the value property of a certain text field, given that the reference to it is stored in the searchBox variable, using a construct of the form searchBox.value . You can place the cursor in this text field by calling its method searchBox.focus() .

Perhaps this is where you can complete our “short course on DOM” and go, in fact, to the little-known properties and methods of DOM interfaces of HTML elements.

If you want to read and experiment right away - open the browser’s developer tools. In particular, in order to get a link to a certain page element, you can select it in the element tree, and then use the $0 construct in the console . To view an item as an object, type dir($0) in the console. And by the way, if you stumble upon something new for you, try exploring it with the console.

# 1: table methods


The modest <table> element (which still holds the first place among the technologies used in the development of web page layouts) has a good number of very good methods that greatly simplify the process of constructing tables.

Here are some of them.

 const tableEl = document.querySelector('table'); const headerRow = tableEl.createTHead().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'; 

As you can see, here we do not use commands like document.createElement() . And the .insertRow() method, if you call it directly for a table, will even add <tbody> . Isn't it great?

# 2: scrollIntoView () method


Probably you know that if the link has a construction like #something , then after the page loads, the browser automatically scrolls it to the element with the corresponding ID ? Admission is convenient, but in the event that the element of interest to us is rendered after the page loads, it will not work. Here's how you can independently recreate this pattern of behavior:

 document.querySelector(document.location.hash).scrollIntoView(); 

No. 3: property hidden


Here we consider the property, however, most likely, when accessing this property, a certain setter will be called, which is a method. In any case, remember, have you ever used the construction shown below to hide an element?

 myElement.style.display = 'none' 

If you use it, you should not do this anymore. To hide an element, it is enough to write true to its hidden property:

 myElement.hidden = true 

# 4: toggle () method


In fact, this is not a method of some element. This is the element property method. In particular, this method allows you to add classes to an element and remove them from it using the following construction:

 myElement.classList.toggle('some-class') 

By the way, if you have ever added classes using the if construct, know that you don’t have to do this anymore, and forget about this construct. The same mechanism is implemented using the second parameter of the toggle() method. If this is an expression that evaluates to true , then the class passed to toggle() will be added to the element.

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

Probably, here you may have doubts about the adequacy of this design. After all, the name of the method, “toggle”, which, given that the essence of the action it performs, can be translated as “toggle,” does not contain any mention of the fact that “switching” implies the fulfillment of a certain condition. However, the above construction exists in this form, although the developers of Internet Explorer, probably also consider it strange. In their implementation of toggle() second parameter is not provided. Therefore, although it was said above that those who know about toggle() , you can forget about the if construct, forget about it, nevertheless, you should not.

# 5: querySelector () method


You definitely already know about the existence of this method, but there is a suspicion that exactly 17% of you do not know that it can be used to apply to any element.

For example, the construction myElement.querySelector('.my-class') will select only those elements that have the class my-class and are also descendants of the element myElement .

# 6: the closest () method


All elements that support searching by parent elements have this method. This is something like the opposite of querySelector() . Using this method, you can, for example, get a header for the current section:

 myElement.closest('article').querySelector('h1'); 

Here, during the search, the first parent element <article> first detected, and then the first element <h1> is included in it.

# 7: getBoundingClientRect () method


The getBoundingClientRect() method returns a nicely designed small object containing information about the dimensions of the element for which this method was called.

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

However, using this method you need to be careful, in particular, paying attention to two points:


# 8: matches () method


Suppose we need to check whether a certain element has a certain class.

Here's how to solve this problem, apparently, in the most difficult way:

 if (myElement.className.indexOf('some-class') > -1) { //  -  } 

Here is another option, it is better, but also far from ideal:

 if (myElement.className.includes('some-class')) { //  -  } 

And here is the best way to solve this problem:

 if (myElement.matches('.some-class')) { //  -  } 

# 9: insertAdjacentElement () method


This method is similar to appendChild() , but gives a little more power over where exactly the descendant element will be added.

So, the parentEl.insertAdjacentElement('beforeend', newEl) command is similar to the parentEl.appendChild(newEl) , but using the insertAdjacentElement() method, in addition to the beforeend argument, you can pass it the arguments beforebegin , afterbegin and afterend , indicating the right place add item.

# 10: contains () method


Have you ever wanted to know if one element is inside another? I need it all the time. For example, if during the processing of a mouse click event you need to know whether it happened inside the modal window or outside of it (which means that you can close it), you can use the following construction:

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

Here, modalEl is the link to the modal window, and e.target is any item that is clicked. What is interesting, when I use this technique, I never get to write everything right the first time, even when I remember that I am constantly mistaken here and try to correct possible mistakes in advance.

# 11: getAttribute () method


Perhaps this method can be called the most useless, however, there is one situation in which it can certainly come in handy.

Remember, we said above that properties of DOM objects are usually associated with attributes of HTML elements?

One of the cases where this is not the case is represented by the href attribute, such as for example: <a href="/animals/cat">Cat</a> .

The el.href construct el.href not return, as you might expect, /animals/cat . This happens because the <a> element implements the HTMLHyperlinkElementUtils interface, which has many auxiliary properties like protocol and hash that help figure out the details about the links.
One of these auxiliary properties is the href property, which gives a full URL, which includes everything that the relative URL in the attribute does not have.

As a result, in order to get exactly what is written in the href attribute, you need to use the el.getAttribute('href') construction.

# 12: three methods of the <dialog> element


A relatively new element <dialog> has two useful, but quite common methods, and one method that can be called simply remarkable. So, the show() and close() methods do exactly what you can expect from them, showing and hiding the window. We call them useful, but ordinary. But the showModal() method will show the <dialog> element on top of everything else, putting it in the center of the window. As a matter of fact, such behavior is usually expected from modal windows. When working with such elements, you do not need to think about the z-index property, manually add a blurred background, or listen to the Escape key press event in order to close the corresponding window. The browser knows how modal windows should work and will ensure that everything acts as it should.

# 13: forEach () method


Sometimes, when you get a link to a list of items, you can forEach() through these items using the forEach() method. The for() loops are yesterday. Suppose we need to log the links of all the <a> elements from the page. If you do this as shown below, we will encounter an error message:

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

In order to solve this problem, you can use the following construction:

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

The point here is that methods like getElementsByTagName() return an object of type HTMLCollection , and querySelectorAll object. It is the interface of the NodeList object NodeList gives us access to the forEach() method (as well as the keys() , values() and entries() methods).

In fact, it would be much better if such methods would simply return ordinary arrays, and would not offer us something that has some kind of useful methods that are not quite similar to arrays. However, you shouldn’t be upset because of this, as smart people from ECMA gave us a great method - Array.from() , which allows you to turn everything into arrays that looks like arrays.

As a result, you can write the following:

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

And here's another nice little thing. Transforming into an array of what used to be just like it, we are able to use a variety of array methods, such as map() , filter() and reduce() . Here, for example, how to form an array of external links available on the page:

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

By the way, I really like the design of .filter(Boolean) because when I meet it sometime in the code I have written long ago, I will not be able to immediately understand its meaning.

# 14: working with forms


You are very likely to know that the <form> element has a submit() method. However, it’s less likely that you know that the forms have a reset() method and that they have a reportValidity() method, which is applicable in cases where validation of form elements is used.

When working with forms, in addition, you can use their elements property, which, through a dot, allows you to access form elements using their name attributes. For example, the myFormEl.elements.email construction will return the <input name="email" /> element belonging to the form ("owned" does not necessarily mean "being a descendant").

It should be noted here that the elements property itself does not return a list of ordinary elements. It returns a list of controls (and this list is, of course, not an array).

Here is an example. If there are three radio buttons on the form and they all have the same name ( animal ), then the formEl.elements.animal construction will give a link to the set of radio buttons (1 control, 3 HTML elements). And if you use the formEl.elements.animal.value construction, it will formEl.elements.animal.value value of the radio button selected by the user.

If you think about it, then all this looks rather strange, so let's look at the previous example:


# 15: select () method


Perhaps at the very end of the material it would be better to talk about some absolutely amazing method, although maybe this method will be a discovery for someone. So, the .select() method allows you to select text in the input fields for which it is called.

Results


In this article, we talked about little-known methods and properties that can be used to work with the contents of web pages. We hope that you have found something new for yourself here, and, perhaps, not only new, but also useful.

Dear readers! Do you use any means of programmatic interaction with the contents of web pages that are not widely known?

Source: https://habr.com/ru/post/416539/


All Articles