如何用 JavaScript 使用 getElementByClass 代替 GetElementById?

我试图根据每个 DIV 的类在网站上切换某些 DIV 元素的可见性。我使用一个基本的 JavaScript 代码片段来切换它们。问题是脚本只使用 getElementById,因为 JavaScript 不支持 getElementByClass。不幸的是,我不得不使用 class 而不是 id 来命名 DIV,因为 DIV 名称是由我的 XSLT 样式表使用某些类别名称动态生成的。

我知道某些浏览器现在支持 getElementByClass,但是因为 Internet Explorer 不支持,所以我不想走这条路。

我已经找到了使用函数按类获取元素的脚本(比如这个页面上的 # 8: http://www.dustindiaz.com/top-ten-javascript/) ,但是我不知道如何将它们与我的切换脚本集成在一起。

这里是 HTML 代码。 DIV 本身缺失了,因为它们是用 XML/XSLT 在页面加载时生成的。

主要问题: 如何让下面的切换脚本按类获取元素而不是按 ID 获取元素?

<html>


<head>


<!--This is the TOGGLE script-->
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>


</head>


<!--the XML/XSLT page contents will be loaded here, with DIVs named by Class separating dozens of li's-->


<a href="#" onclick="toggle_visibility('class1');">Click here to toggle visibility of class 1 objects</a>


<a href="#" onclick="toggle_visibility('class2');">Click here to toggle visibility of class 2 objects</a>


</body>
</html>
429611 次浏览

Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname'

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".classname").hide();
});
</script>

The getElementsByClassName method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:

function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) { // use native implementation if available
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;


for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}

Usage:

function toggle_visibility(className) {
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];


if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
}

adding to CMS's answer, this is a more generic approach of toggle_visibility I've just used myself:

function toggle_visibility(className,display) {
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];


if(display.length > 0) {
e.style.display = display;
} else {
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
}
}

My solution:

First create "<style>" tags with an ID.

<style id="YourID">
.YourClass {background-color:red}
</style>

Then, I create a function in JavaScript like this:

document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'

Worked like a charm for me.

Use it to access class in Javascript.

<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>
document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';

Acyually by using getElementsByClassName, it returns an array of multiple classes. Because same class name could be used in more than one instance inside same HTML page. We use array element id to target the class we need, in my case, it's first instance of the given class name.So I've used [0]

You can get the same result using document.querySelectorAll('.klass') as document.getElementsByClassName(klass).

It might not seem like much but querySelectorAll allows queries on any CSS selector which makes it much more flexible, in case "get all elements by class name" is just a step in what you are really trying to do. It is vanilla JS answer to jQuery's $('.class').

Source:

https://stackoverflow.com/a/9427330/3850405