Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  49] [ 7]  / answers: 1 / hits: 21863  / 8 Years ago, tue, february 16, 2016, 12:00:00

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.


More From » javascript

 Answers
3

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


[#63302] Saturday, February 13, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kelleyamiahk

Total Points: 216
Total Questions: 113
Total Answers: 119

Location: Serbia
Member since Tue, Jul 26, 2022
2 Years ago
;