15 HTML methods of elements that you have probably never heard of

    From the translator: David Gilbertson (David Gilbertson) is a famous author who writes about web and cryptocurrency technologies. He was able to gather a large audience of readers, which tells about all the tricks and interesting things in these areas.



    A quick introduction

    Let's discuss the difference between HTML and DOM.

    For example, take a table element from HTML. You can use it in a file with the .html extension. In it, we specify a set of attributes that define the appearance and "behavior" of the page.

    And that's all, there is nothing in common with JavaScript.

    DOM is what allows you to combine your JavaScript code with HTML elements in a document, so that you can interact with them as with objects.

    This is a document-in-object model.

    Any type of element in HTML has its own DOM “interface” that defines properties and methods. For example, table has an interface called HTMLTableElement .

    You can get a link to a specific item by writing something like this:

    image

    You have access to all the properties and methods that are available for a particular type of item. For example, you can access the value properties by using searchBox.value, or set the cursor to a specific position using searchBox.focus ().

    Now let's discuss one more important thing: most of the elements do not have interesting methods, so it is easy to miss something important, if you don’t dive into this question on purpose.

    But, fortunately, attention to detail and the study of specifications is my forte. Therefore, I did everything I needed and write about the results in this article.

    If you want to try to figure out the DOM yourself, you should use the browser tools to explore some of the elements. To do this, select one of them in the element tree and type $ 0 in the console. This will give you a link to the item you selected. To convert it to an object, type dir ($ 0).

    There are a lot of things you can do in the console .



    Skillbox recommends: an online course Web developer We
    remind: For all Habr's readers - a discount of 10,000 rubles when writing to any Skillbox course on the promo code "Habr".

    №1. Table methods


    There are quite a few convenient methods that allow you to assemble tables like furniture in Ikea.

    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';

    Here you see not only document.createElement (). For example, the .insertRow () method will embed tbody if you are organizing a call to this element right in the tree. Isn't that cool?

    №2. scrollIntoView ()


    Do you know that if you have #something in the URL, then when the page loads the browser will scroll it to the element with this ID?

    This usually helps a lot, but does not work if you render this item after the page loads. To take advantage of the feature described above, simply prescribe document.querySelector (document.location.hash) .scrollIntoView ();

    Number 3. hidden


    Well, yes, it seems to be not a method, but since there is a setter (property setting method), then it can be considered a method.

    Anyway, have you ever used myElement.style.display = 'none' to hide an element? If yes, then do not do it.

    Where better to use myElement.hidden = true.

    №4. toggle ()


    We can use this method to add or remove an element class using myElement.classList.toggle ('some-class').

    And if you have ever added a class using if, then think: maybe it's worth trying something else?

    For example, you can simply use the second parameter for the toggle method. It is necessary to transfer it to the switching method. If this happens, your class will be added to the element:

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

    Yes, I understand what you are thinking now: this is not what the word “toogle” itself means. Those behind Internet Explorer? agree with this and express their protest without using the second parameter at all.

    But let's get it back. Freedom parameters!

    №5. querySelector ()


    Well, well, you should definitely know this, but I suspect that approximately 17% of readers do not know how to use this method in conjunction with elements.

    Example: myElement.querySelector ('. My-class') will match the elements that have the class my-class and the “descendants” myElement.

    №6. closest


    This method is available for all elements that view the element tree. This is something like a reverse for querySelector (). Therefore, we can use the title of the current section as follows:

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

    We start with article and end with h1 first .

    №7. getBoundingClientRect ()


    The method returns an object with detailed information about the item we specified.

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

    But be careful: the above example causes a redraw. Depending on the device and the complexity of your page, this may take a few milliseconds. Therefore, keep this in mind if you call it again, for example in an animation.

    Not all browsers return all of these values.

    №8. matches ()


    I would like to check if a particular element belongs to a particular class.

    Maximum difficulty:

    if (myElement.className.indexOf('some-class') >-1) {
      // do something
    }
    Немного лучше, но все равно не то:
    if (myElement.className.includes('some-class')) {
      // do something
    }

    Exactly what is needed:

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

    №9. insertAdjacentElement ()


    I discovered it today! This is similar to appendChild (), but gives a little more control in the process of adding a child.

    parentEl.insertAdjacentElement ('beforeend', newEl) does about the same thing as parentEl.appendChild (newEl), but you can specify beforebegin, afterbegin or afterend to put it in the place that these names indicate.

    How much control!

    №10. contains ()


    Have you ever wanted to know if there is an element inside another? I want to know this all the time.

    For example, if I process a mouse click and want to understand whether it happened inside or outside (so that I can close it), I do this:

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

    Here, modal El is a reference to a modal window, and e.target is the element that is clicked.

    It's funny, but I often make mistakes in logic when I first try to use a method. And then when I try to correct the error, I am wrong again. And this method helps to immediately deal with it.

    №11. getAttribute ()


    One of the most useless element methods, but not in this particular case.

    Do you remember that properties usually refer to attributes?

    Sometimes this is not the case, for example, when href is an attribute of an element, for example a href = "/ animals / cat"> Cat </ a.

    el.href will not give us / animals / cat, as might be expected. This is because the element executes the HTMLHyperlinkElementUtils interface, which is a bunch of supporting properties like protocol and hash pointing to the link object.

    This is one of the useful properties of href, which will give the full L, rather than a relative URL in the attribute.

    Thus, you must use el.getAttribute ('href') if you need a literal string inside the href attribute.

    №12. dialog


    The relatively new dialog element has two good methods and one perfect one. show () and close () do exactly what is expected of them. And that's good, I suppose.

    But showModal () will display a dialog on top of any other elements placed on the page. There is no need for z-index, or manually adding a dim background, or tracking the pressing of the Escape button. The browser knows how modal windows work, and does everything for you. And this is great.

    №13. forEach ()


    Sometimes, when you need to refer to a list of items, you can use forEach ().

    But what if you need to log all URLs for all links on a page? You can do this and see the error.

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

    Or do this:

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

    The fact is that getElementsByTagName and other get methods ... return an HTMLCollection, but querySelectorAll returns a NodeList.

    And the NodeList interface gives us a forEach () method (along with the keys (), values ​​() and entry ()).

    The good ECMA guys gave us Array.from (), which turns everything that looks like an array into an array itself.

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

    Bonus! When creating an array, you can use map (), and filter (), and reduce () or any other method. For example, returning an array of external links:

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

    I like to prescribe .filter (Boolean), because without it I would have to scratch my head in the future, trying to remember what it is and how it works.

    №14. Forms


    The form , as you most likely already know, has a submit () method. It is somewhat less likely that you know that forms have a reset () method and can report a value of Validity () if you use validation on your form elements.

    You can also use the dot-notation property of form elements to reference an element by its name attribute. For example, myFormEl.elements.email will return the input name = "email" / element that belongs to the form ("owned" does not necessarily mean that it is its "descendant").

    But now I lied. The fact is that elements do not return a list of elements. It returns a list of controls (and, of course, this is not an array).

    Example: if you have three radio buttons, each with the same animal name, then formEl.elements.animal will give you a link to this set of radio buttons (1 control, 3 elements).

    And formEl.elements.animal.value will return the value of the selected radio button.

    This is a strange syntax, if you think about it. Break it down guys: formEl is an element, elements are an HTMLFormControlsCollection, not-quite-an array, where each element is not necessarily an HTML element. Animal has several switches that are united only because they have the same name attribute (for this there is the RadioNodeList interface), and the value looks at the value attribute of any switch in the collection.

    №15. select ()


    The .select () method will select all the text in any input you call.

    Thank you for reading, I hope all this will be useful for you. Always check the capabilities of your browser, so that later it was not painfully painful.

    Practical from Skillbox , which will help a novice programmer to become a sought-after specialist:


    Also popular now: