问题
I'm trying to target Safari(both mobile and desktop)
and append some styles for a class via Javascript
.
This is how my code looks like.
(function safaristyles()
{
if (navigator.userAgent.match(/AppleWebKit/) && ! navigator.userAgent.match(/Chrome/)) {
var avt = document.getElementsByClassName("avatar");
avt.style.border = "0" + "px";
avt.style.padding = "0" + "px";
}
})(this);
As I see it in Webkit inspector
, this is the error I'm facing.
Type Issue - 'undefined' is not an object (evaluating 'avt.style.border = "0" + "px")
I'm a beginner at JS stuff, so please bear with me.
回答1:
document.getElementsByClassName("avatar");
will return you elements is a HTMLCollection of found elements.
so if you have just one item this would work
avt[0].style.border = "0" + "px";
avt[0].style.padding = "0" + "px";
if you have multiple items use a for loop.
here is a simple fiddle for something similar
http://jsfiddle.net/qjreK/1/
Check these out for more details
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName
http://www.w3schools.com/htmldom/dom_using.asp
回答2:
document.getElementsByClassName() returns a set of elements. If you want to change the style of a class, I see two good options:
- Append a style tag with the new class style.
- Make a loop and change each item of the
document.getElementsByClassName()
's list.
I would recomment to use the first method, because it would allow you to add new elements with that class without needing to change it's style.
回答3:
The method getElementsByClassName just return the nodeList match that classname which you pass in, but not array.
You can convert this nodeList to array and set the single item's style
var avt = Array.prototype.slice.call(avt, 0);
avt[0].style.padding = "0px";
来源:https://stackoverflow.com/questions/17769563/using-getelementbyclassname-in-safari