How can I target a span by its classname?
I want the innerHTML of some spans that do not have a unique ID but they do have unique Classes
I want to do something like var1 = document.getElementByCLASSNAME('')
edit:
I can't use Jquery, hell i cant even give开发者_如何学Python elements propper ID's. long story
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1
&& hasClassName.test(elementClass))
results.push(element);
}
return results;
}
Based on this post on devshed: Get all elements of class 'abc'
There is a getElementsByClassName
method (supported by the latest versions of major browsers) that returns a list of all elements with the specified class. Of course, many users still have older browsers, so a simpler solution is to use a library such as jQuery and select elements with $('.someclass')
.
Using getElementsByClassName may cause problems with versions of IE. querySelectorAll should be more widely compatible. i.e. document.querySelectorAll('.my-class') or document.querySelectorAll('div.my-class')
精彩评论