15 obscure properties and methods of DOM objects
- Transfer
When developing modern web sites, JavaScript features for working with DOM are used extensively. Scripts allow you to display and hide the elements from which the 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 tell about here are much less popular.
First, let's talk about the difference between HTML code and DOM. For example, a regular element
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 element
You can get a link to a certain element, for example, using the following construction:
After the link to the element is obtained, the programmer has access to the properties and methods that similar elements have. For example, you can work with the property of
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 for 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 construction
The modest element
Here are some of them.
As you can see, here we do not use teams like
Probably you know that if the link has a view structure
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?
If you use it, you should not do this anymore. In order to hide an element, it is enough to write
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:
By the way, if you have ever added classes using a construct
Probably, here you may have doubts about the adequacy of this design. After all, the name of the method, “toggle”, which, given that it contains the essence of the action it performs, can be translated as “toggle,” does not contain any mention that “switching” implies the fulfillment of some condition. However, the above construction exists in this form, although the developers of Internet Explorer, probably also consider it strange. In their implementation, the
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, a construction
All elements that support searching by parent elements have this method. This is something like the opposite option
Here, during the search, the first parent element is first detected
The method
However, using this method you need to be careful, in particular, paying attention to two points:
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:
Here is another option, it is better, but also far from ideal:
And here is the best way to solve this problem:
This method is similar to
So, the command is
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:
Here
Perhaps this method can be called the most useless, however, there is one situation in which it can definitely come in handy.
Remember, we mentioned above that the properties of DOM objects are usually associated with attributes of HTML elements?
One of the cases where it is not, is represented by an attribute
The design
One of these auxiliary properties is the property
As a result, in order to get exactly what is written in the attribute
A relatively new element
Sometimes, when you get a link to a list of items, you can iterate through these items using a method
In order to solve this problem, you can use the following construction:
The point here is that methods like
In fact, it would be much better if such methods simply returned ordinary arrays, rather than offering us something that has some kind of useful methods that are not quite similar to arrays. However, it is not worth it to get upset because the smart people from ECMA gave us a great method -
As a result, you can write the following:
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
By the way,
You are very likely to know that the element
When working with forms, in addition, you can use their property
Here it should be noted that the property itself
Here is an example. If there are three radio buttons on the form and they all have the same name (
If you think about it, then all this looks rather strange, so let's look at the previous example:
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 method
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?
HTML and DOM
First, let's talk about the difference between HTML code and DOM. For example, a regular element
<table<
is obviously HTML. This element can be used in html-files, it has a set of attributes that defines the appearance and behavior of the table created with its help. In fact, the tag <table>
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). 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 element
<table>
there is an interface called HTMLTableElement . You can get a link to a certain 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, you can work with the property of
value
a certain text field, given that the reference to it is stored in a variable searchBox
, using the view construct 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 for 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 construction
$0
inconsole . To view an item as an object, enter the command in the console dir($0)
. And by the way, if you stumble upon something new for you, try exploring it with the console.# 1: table methods
The modest element
<table>
(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 designing 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 teams like
document.createElement()
. And the method .insertRow()
, if you call it directly for the table, will even provide an addition <tbody>
. Isn't it great?# 2: scrollIntoView () method
Probably you know that if the link has a view structure
#something
, then after the page loads, the browser automatically scrolls it to the element with the corresponding one 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. In order to hide an element, it is enough to write
true
in its property hidden
: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 a construct
if
, know that you will not have to do this anymore, and forget about this construct. The same mechanism is implemented using the second parameter of the method toggle()
. If this is an expression whose calculation yields true
, then the class passed toggle()
in 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 it contains the essence of the action it performs, can be translated as “toggle,” does not contain any mention that “switching” implies the fulfillment of some condition. However, the above construction exists in this form, although the developers of Internet Explorer, probably also consider it strange. In their implementation, the
toggle()
second parameter is not provided. Therefore, although it was said above that those who know about toggle()
can forget about the construction if
, forget about it, still, 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, a construction
myElement.querySelector('.my-class')
will select only those elements that have a class my-class
and are at the same time descendants of an element myElement
.# 6: the closest () method
All elements that support searching by parent elements have this method. This is something like the opposite option
querySelector()
. Using this method, you can, for example, get a title for the current section:myElement.closest('article').querySelector('h1');
Here, during the search, the first parent element is first detected
<article>
, and then the first element entering into it <h1>
.# 7: getBoundingClientRect () method
The method
getBoundingClientRect()
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:
- Calling this method causes the page to be redrawn. Depending on the device on which the page is being viewed, and on the complexity of the page, this operation may take several milliseconds. Keep this in mind if you are going to call this method in some repetitive code fragments, for example, when you are animating.
- Not all browsers support this method.
# 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 command is
parentEl.insertAdjacentElement('beforeend', newEl)
similar to the command parentEl.appendChild(newEl)
, but using the method insertAdjacentElement()
you can, in addition to the argument beforeend
, pass arguments to it beforebegin
, afterbegin
and afterend
indicating the place where the element should be added.# 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 element that is clicked with the mouse. 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 fix 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 definitely come in handy.
Remember, we mentioned above that the properties of DOM objects are usually associated with attributes of HTML elements?
One of the cases where it is not, is represented by an attribute
href
, for example, such as here: <a href="/animals/cat">Cat</a>
. The design
el.href
will not return, as might be expected /animals/cat
. This is due to the fact that the element <a>
implements the HTMLHyperlinkElementUtils interface , which has many auxiliary properties like protocol
and hash
which help to clarify details about the links. One of these auxiliary properties is the property
href
which gives a complete URL that 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 attribute
href
, you need to use the construction el.getAttribute('href')
.# 12: three methods of the <dialog> element
A relatively new element
<dialog>
has two useful, but quite ordinary methods, and one method, which can be called simply remarkable. So, the methods show()
and close()
perform exactly what you can expect from them, showing and hiding the window. We call them useful, but ordinary. But the method showModal()
will show the element <dialog>
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 property z-index
, manually add a blurred background, or listen to a key press event in Escape
order to close the corresponding window. The browser knows how modal windows should work and will take care that everything works as it should.# 13: forEach () method
Sometimes, when you get a link to a list of items, you can iterate through these items using a method
forEach()
. Cycles for()
are yesterday. Suppose we need to log the links of all the elements <a>
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 the querySelectorAll
object NodeList
. It is the object's interface that NodeList
gives us access to the method forEach()
(and also to methods keys()
, values()
and entries()
). In fact, it would be much better if such methods simply returned ordinary arrays, rather than offering us something that has some kind of useful methods that are not quite similar to arrays. However, it is not worth it to get upset because the 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,
.filter(Boolean)
I really like the design 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 element
<form>
has a method submit()
. However, it’s less likely that you know that the forms have a method reset()
, and that they have a method reportValidity()
that is applicable in cases where validation of filling in form elements is used. When working with forms, in addition, you can use their property
elements
, which, through a dot, allows you to access form elements using their attributes name
. For example, a construct myFormEl.elements.email
will return an element <input name="email" />
belonging to a form (“owned” does not necessarily mean “being a descendant”). Here it should be noted that the property itself
elements
does not return a list of regular items. It returns a list of controls (and this list, of course, is 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 design formEl.elements.animal
will give a link to a set of radio buttons (1 control, 3 HTML elements). And if you use the design formEl.elements.animal.value
, it will give the 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:
formEl
- this is an item.elements
- this is an HTMLFormControlsCollection object , resembling an array, but it is not. Its elements are not necessarily HTML elements.animal
- is a set of several radio buttons, presented as a set due to the fact that they all have the same attributename
(there is an interface RadioNodeList , designed specifically for working with radio buttons).value
used to access the attribute of thevalue
active radio button in the collection.
# 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 method
.select()
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?