0

I'm trying to find a class on a div (where the value will always end in 0bg), given a partial string, and then get its background style value.

For example:

.xx-color-100bg{
    background-color: #323334;
}
<div class="heading xx-color-100bg"></div>
document.querySelectorAll(".heading").classList.contains("0bg").style.background

The solution above errors with Cannot read properties of undefined (reading 'contains')

How can I find the necessary class and grab it's background-color value?

3
  • querySelectorAll() returns a NodeList. classList is undefined on NodeList (it is found on a DOMElement Commented Apr 12, 2022 at 18:40
  • I wonder if this is good enough: .querySelectorAll('[class$="0bg"]') Commented Apr 12, 2022 at 18:42
  • You can include the 0bg in your querySelector, ".heading[class$='0bg']" Commented Apr 12, 2022 at 18:43

2 Answers 2

1

querySelectorAll() returns a NodeList, so you can't use classList. You need to loop over the DOMElements in the list or just assume the first one is what you need:

document.querySelectorAll(".heading").forEach(e => {
    // do something with e.classList
});

// OR

document.querySelectorAll(".heading")[0].classList // the first element
Sign up to request clarification or add additional context in comments.

Comments

0

Figured out the solution right after posting the question:

window.getComputedStyle(document.querySelector(".heading[class*='0bg'")).backgroundColor;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.