Home > database >  How to parse document.getElementsByClassName to only include a child with an alt="value"
How to parse document.getElementsByClassName to only include a child with an alt="value"

Time:12-01

How can I change the JavaScript to change the style to "none" of all the <div > that have an <img> with the alt="long" and not the other ones.

I don't want to use JQuery.

Example HTML:

<div >
    <img alt="long" >
</div>


<div >
    <img alt="short" >
</div>

JavaScript:

ar = document.getElementsByClassName('class1');
for (i = 0; i < ar.length;   i)
  ar[i].style.display = "none";

This Changes both div above... How can I modify the getElementsByClassName() to only include the ones with <img alt="long">

CodePudding user response:

Use Document.querySelectorAll() instead with a query that locates all the <img> tags with the alt attribute values you're after that are descendants of elements.

Then, navigate up to the <div> parent and set its style

document.querySelectorAll("div.class1 img[alt=long]").forEach((img) => {
  img.closest("div.class1").style.display = "none";
});
div { padding: 1rem; margin-bottom: 1rem; border: 1px solid #ccc; width: max-content; }

.class1 { border-color: blue; }
<div >
  <img alt="long" src="https://picsum.photos/seed/long/200/100">
</div>

<div >
  <img alt="short" src="https://picsum.photos/seed/short/200/100">
</div>

<div >
  <img alt="long" src="https://picsum.photos/seed/long/200/100">
</div>

CodePudding user response:

You should use document.querySelectorAll to do proper query and get all img with given attribute. Then you should use parentElement

I think something like this

document.querySelectorAll('[alt=long]').forEach(el => el.parentElement.style.display = 'none')

should resolve your problem

  • Related