如何使用 JavaScript getElementByClass 而不是 GetElementById?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1933602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:57:54  来源:igfitidea点击:

How to getElementByClass instead of GetElementById with JavaScript?

javascriptclasstogglegetelementbyidgetelementsbyclassname

提问by Alan

I'm trying to toggle the visibility of certain DIV elements on a website depending on the class of each DIV. I'm using a basic JavaScript snippet to toggle them. The problem is that the script only uses getElementById, as getElementByClassis not supported in JavaScript. And unfortunately I do have to use class and not id to name the DIVs because the DIV names are dynamically generated by my XSLT stylesheet using certain category names.

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

I know that certain browsers now support getElementByClass, but since Internet Explorer doesn't I don't want to go that route.

我知道某些浏览器现在支持getElementByClass,但由于 Internet Explorer 不支持,我不想走那条路。

I've found scripts using functions to get elements by class (such as #8 on this page: http://www.dustindiaz.com/top-ten-javascript/), but I can't figure out how to integrate them with with my toggle script.

我发现使用函数按类获取元素的脚本(例如本页上的#8:http: //www.dustindiaz.com/top-ten-javascript/),但我不知道如何集成它们与我的切换脚本。

Here's the HTML code. The DIVs themselves are missing since they are generated on page load with XML/XSLT.

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

Main Question: How do I get the below Toggle script to get Element by Class instead of get Element by ID?

主要问题:如何获取以下 Toggle 脚本以按类获取元素而不是按 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>

采纳答案by Sampson

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.

现代浏览器支持document.getElementsByClassName. 您可以在caniuse 上查看提供此功能的供应商的完整分类。如果您希望将支持扩展到旧浏览器,您可能需要考虑使用 jQuery 或 polyfill 中的选择器引擎。

Older Answer

较旧的答案

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

您需要检查jQuery,它将允许以下内容:

$(".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:

Google 提供了一个托管的 jQuery 源文件,因此您可以参考它并立即开始运行。在您的页面中包含以下内容:

<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>

回答by CMS

The getElementsByClassNamemethod 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:

getElementsByClassName方法现在被最新版本的 Firefox、Safari、Chrome、IE 和 Opera 原生支持,您可以创建一个函数来检查本地实现是否可用,否则使用 Dustin Diaz 方法:

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';
     }
  }
}

回答by Vishwa

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]

通过使用 getElementsByClassName,它返回一个包含多个类的数组。因为同一个类名可以在同一个 HTML 页面中的多个实例中使用。我们使用数组元素 id 来定位我们需要的类,在我的例子中,它是给定类名的第一个实例。所以我使用了 [0]

回答by Manvendra Priyadarshi

Use it to access class in Javascript.

使用它来访问 Javascript 中的类。

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

回答by cregox

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

添加到CMS 的答案中,这是toggle_visibility我自己使用的一种更通用的方法:

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';
       }
     }
  }
}

回答by thylorion

My solution:

我的解决方案:

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

首先创建带有 ID 的“<style>”标签。

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

Then, I create a function in JavaScript like this:

然后,我在 JavaScript 中创建一个函数,如下所示:

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

Worked like a charm for me.

对我来说就像一种魅力。

回答by Reltpid

Append IDs at the class declaration

在类声明中附加 ID

.aclass, #hashone, #hashtwo{ ...codes... }
document.getElementById( "hashone" ).style.visibility = "hidden";