Matt
Matt

Reputation: 1609

Find css class on div and get values

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?

Upvotes: 0

Views: 71

Answers (2)

Matt
Matt

Reputation: 1609

Figured out the solution right after posting the question:

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

Upvotes: 0

0xLogN
0xLogN

Reputation: 3823

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

Upvotes: 1

Related Questions