How to tag with javascript

Asked

Viewed 163 times

0

My site has some pictures and I want that when the person click on a button, it will call the function that will "transform" all the images of the tag img in:

display none;

Without having to take every ID from an image, I want something like

document.querySelector("img");

And let this dial take all the tag img, I tried to be as clear as I could.

2 answers

3


To get a list of all the HTML elements of a given tag use the function getelementsbytagname, it will return you a list of all page elements

document.getElementsByTagName('img');

To take this listing and change the property display for none use the code below:

for (let image of document.getElementsByTagName("img")) {
   image.style.display = 'none';
}
  • Thank you kkkk was looking wrong.

2

The method document.querySelector will return only the first element that satisfy the selector informed in the first argument.

If you want to get the complete list of all elements that satisfy the informed selector, you must use the method document.querySelectoraAll, that returns a NodeList. With it, you must iterate over each element to make individual modifications.

const button = document.querySelector('button');

button.addEventListener('click', () => {
  const els = document.querySelectorAll('strong');
  
  els.forEach((el) => {
    el.style.display = 'none';
  });
});
<strong>Foo</strong>
<strong>Bar</strong>
<strong>Baz</strong>
<strong>Qux</strong>

<button>Remover</button>

You can also use the method document.getElementsByTagName, which has a higher support. However, I find the querySelectorAll most convenient.

  • Got it, thanks, I will use Document.getelementsbytagname found simpler.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.