Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - add css style to element with class

Tags:

javascript

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.

like image 816
Robson Avatar asked Feb 16 '16 13:02

Robson


Video Answer


1 Answers

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";
}
like image 107
brso05 Avatar answered Sep 22 '22 14:09

brso05