Methods and properties chaining in JavaScript

Let us have an input:

<input id="elem" value="text">

Let's display the input text:

let elem = document.querySelector('#elem'); console.log(elem.value); // shows 'text'

As you can see, we first get an element by its id, write this element to the variable elem, and then display the property value from this variable

In fact, you can not enter the variable elem, but build a chain of dots in this way:

console.log( document.querySelector('#elem').value ); // shows 'text'

In the same way - in a chain - you can overwrite attributes:

document.querySelector('#elem').value = 'www';

Given the following code:

<img id="image" src="avatar.png"> let image = document.querySelector('#image'); console.log(image.src);

Modify the code above to use a chain instead of introducing the variable image.

Advantages and disadvantages of chains

Despite the fact that the chains reduce the code, in most cases the introduction of a variable is still more convenient. Compare the two examples - now I have entered the variable elem and I can write any number of attributes, while querySelector is called only once:

let elem = document.querySelector('#elem'); elem.value = 'www'; elem.type = 'submit';

And now I'm not introducing a new variable and so I have to call querySelector twice:

document.querySelector('#elem').value = 'www'; document.querySelector('#elem').type = 'submit';

In my opinion, this code has become more complicated, although it takes one line less. Also, if I want to change the value of id from 'elem' to something else, I have to do it in many places, which is not very convenient.

There is also another problem - the load on the browser. Searching for elements on the page, which is done by the querySelector method, is a rather slow operation (and in general, any work with page elements is a slow operation - remember this).

In our case, if we use querySelector every time, then the browser will process the HTML page each time and look for an element with a given id several times (it doesn’t matter that id are the same - the browser will do all the actions several times), performing useless operations that can slow down the browser.

If we use the variable elem - no search occurs on the page (the element has already been found and the reference to it lies in the variable).

Given the following code:

<img id="image" src="avatar.png" width="300" height="500"> console.log(document.querySelector('#image').src); console.log(document.querySelector('#image').width); console.log(document.querySelector('#image').height);

Point out the disadvantages of this code. Remove them.

enru