Robson
Robson

Reputation: 1277

Javascript - add css style to element with class

I want to add only one css style in JS. I don't want to include jQuery for only one thing.

My code:

document.addEventListener('DOMContentLoaded', function() {
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
        var productAttr = document.getElementsByClassName('product-attributes');
        productAttr.style.top = "-90px";
    }
});

The error from console is:

TypeError: 'undefined' is not an object (evaluating 'productAttr.style.top = "-90px"')

If I want change other styles f.e. opacity or color, I get the same problem.

How can I fix this ?

Thanks in advance for help.

Upvotes: 7

Views: 26563

Answers (4)

Maybe it's because you can not give negative values in CSS

top:"-90px" === bottom "90px"

Maybe now it would work

document.addEventListener('DOMContentLoaded', function() {
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
        var productAttr = document.getElementsByClassName('product-attributes');
        productAttr.style.bottom = "90px";
    }
});

Upvotes: 0

zehata
zehata

Reputation: 3674

It's preferred to have an id assigned to the targeted element then target using getElementById() as there cannot be elements with the same id, hence getElementByClassName() will return an array if there are multiple elements with the same className. If you need to target multiple elements, you should for-loop through them while applying the change to the nth item being looped:

for(x = 0; x < array.length; x++){
    array[x].style.top = '-90px';
}

Gentle reminder: also remember to have position: relative|absolute|fixed to ensure 'top' attribute works

edited with thanks to Sebastien Daniel

Upvotes: -1

PedroZGZ
PedroZGZ

Reputation: 1

When selecting a class you have to indicate what number is as an Tag, it is not like the id that there is only one.

It would be something like this code depending on which of the classes you want to apply it:

document.addEventListener('DOMContentLoaded', function() {
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
        var productAttr = document.getElementsByClassName('product-attributes');
        productAttr[0].style.top = "-90px";
        productAttr[1].style.top = "-90px";
        productAttr[2].style.top = "-90px";
    }
});

Upvotes: -1

brso05
brso05

Reputation: 13222

You need to loop through your results because getElementsByClassName() returns a collection of elements:

for(var i = 0; i < productAttr.length; i++)
{
    productAttr[i].style.top = "-90px";
}

Upvotes: 4

Related Questions