0

Please tell me how to assign values to tags by their attributes:

  • if the attribute is empty - the background is red
  • if there is something in the attribute - the background is blue

Gives error all the time - Uncaught TypeError: elems.getAttribute is not a function

Is it possible to replace getAttribute with something else?

Thank you in advance!

function ifImgIsEmpty() {
    let elems = document.querySelectorAll('.card');
    let value = elems.dataset.databackgroundImage;
  
    for (let elem of elems) {
        if (elem.value === null && elem.value === '') {
            elem.style.background = "red";
        } else {
            elem.style.background = "blue";
        }
    }
  
};
ifImgIsEmpty();
.card {
  display: flex:
  border: solid;
  padding: 2rem;
  background: #eee;
}
<a href="" class="card" data-background-image="">01</a>
<a href="" class="card" data-background-image="blue">02</a>
<a href="" class="card" data-background-image="blue">03</a>
<a href="" class="card" data-background-image="">04</a>
Stan Law
  • 61
  • 6
  • 1
    Document.querySelectorAll() returns a static [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList). See [methods available on NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList#instance_methods) and [methods available on Node](https://developer.mozilla.org/en-US/docs/Web/API/Node#instance_methods). – jarmod Jan 12 '23 at 15:37
  • 2
    `databackgroundimage` is incorrect. It should be `data-background-image`. – Sebastian Simon Jan 12 '23 at 15:41
  • 1
    You need to use `elem.getAttribute('data-background-image')` or `elem.dataset.dataBackgroundImage` in the loop. – Barmar Jan 12 '23 at 15:41
  • 1
    No need for JavaScript. This can be done with simple css. See: https://stackoverflow.com/a/16429347/943435 – Yogi Jan 12 '23 at 15:57

0 Answers0