Javascript 如何在类中使用innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11489716/
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-24 06:02:15  来源:igfitidea点击:

How to use innerHTML with class

javascript

提问by Stranger

I want to use innerHTML with the class as reference. I found lot of examples with id as reference. Do anyone have any idea of how to get the innerHTML of the element without using the id name.

我想使用带有类的 innerHTML 作为参考。我发现了很多以 id 为参考的例子。有没有人知道如何在不使用 id 名称的情况下获取元素的 innerHTML。

Please not that i don't want to use any JavaScript libraries like jquery here.

请注意,我不想在这里使用任何像 jquery 这样的 JavaScript 库。

采纳答案by Mendhak

You can use document.getElementsByClassName, but that will not work pre-IE9. Use this method from a Google Code project, I'm copy-pasting it here

您可以使用 document.getElementsByClassName,但这在 IE9 之前不起作用。在Google Code 项目中使用此方法,我将其复制粘贴到此处

/*
  Developed by Robert Nyman, http://www.robertnyman.com
  Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/  
var getElementsByClassName = function (className, tag, elm){
  if (document.getElementsByClassName) {
    getElementsByClassName = function (className, tag, elm) {
      elm = elm || document;
      var elements = elm.getElementsByClassName(className),
        nodeName = (tag)? new RegExp("\b" + tag + "\b", "i") : null,
        returnElements = [],
        current;
      for(var i=0, il=elements.length; i<il; i+=1){
        current = elements[i];
        if(!nodeName || nodeName.test(current.nodeName)) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  else if (document.evaluate) {
    getElementsByClassName = function (className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = "",
        xhtmlNamespace = "http://www.w3.org/1999/xhtml",
        namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
        returnElements = [],
        elements,
        node;
      for(var j=0, jl=classes.length; j<jl; j+=1){
        classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
      }
      try  {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
      }
      catch (e) {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
      }
      while ((node = elements.iterateNext())) {
        returnElements.push(node);
      }
      return returnElements;
    };
  }
  else {
    getElementsByClassName = function (className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = [],
        elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
        current,
        returnElements = [],
        match;
      for(var k=0, kl=classes.length; k<kl; k+=1){
        classesToCheck.push(new RegExp("(^|\s)" + classes[k] + "(\s|$)"));
      }
      for(var l=0, ll=elements.length; l<ll; l+=1){
        current = elements[l];
        match = false;
        for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
          match = classesToCheck[m].test(current.className);
          if (!match) {
            break;
          }
        }
        if (match) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  return getElementsByClassName(className, tag, elm);
};

Usage:

用法

To get all elements in the document with a “info-links” class.

使用“信息链接”类获取文档中的所有元素。

getElementsByClassName("info-links");

To get all div elements within the element named “container”, with a “col” class.

使用“col”类获取名为“container”的元素中的所有 div 元素。

getElementsByClassName("col", "div", document.getElementById("container"));

To get all elements within in the document with a “click-me” and a “sure-thang” class.

使用“click-me”和“sure-thang”类获取文档中的所有元素。

getElementsByClassName("click-me sure-thang");

Edit: Here's an example

编辑:这是一个例子

First, your Javascript function:

首先,您的 Javascript 函数:

   function ProcessThese()
{
    nodes = getElementsByClassName('hello');
    alert(nodes[0].innerHTML);
    alert(nodes[0].value);  // <-- This gets you what the user typed in
}

Some sample HTML:

一些示例 HTML:

<br />

<textarea class="hello">222</textarea>

<br />

<input type="button" onclick="ProcessThese();" value="Click me" />

Click the button on the page and it should grab the values out.

单击页面上的按钮,它应该抓取值。

回答by xdazz

You could try Document.querySelector(if you only want the first element) or Document.querySelectorAll(if you want to get all elements).

您可以尝试Document.querySelector(如果您只想要第一个元素)或Document.querySelectorAll(如果您想获取所有元素)。

var el = document.querySelector(".myclass"); 
var html = el.innerHtml;

回答by g13n

Its all about how you grab the element reference. Here's how you can do with classes.

这完全取决于您如何获取元素引用。以下是您可以如何处理课程。

var items = document.getElementsByClassName("my-class"),
    i, len;

// loop through all elements having class name ".my-class"
for (i = 0, len = items.length; i < len; i++) {
    items[i].innerHTML = "...";
}

Of course older browsers don't support document.getElementsByClassName() so you can use either jQuery/YUI or some library since it handles older browsers.

当然,较旧的浏览器不支持 document.getElementsByClassName(),因此您可以使用 jQuery/YUI 或某些库,因为它可以处理较旧的浏览器。

回答by Ehryk

The reason id is used is because IDs are unique: class names are not. In the text of your question you ask how to get the innerHTML of 'the element', but this could be incorrect. Unlike ids which will either be a single element or null, you could have 15 elements with the same class name (and likely do).

使用 id 的原因是因为 ID 是唯一的:类名不是。在您的问题文本中,您询问如何获取“元素”的innerHTML,但这可能不正确。与 id 要么是单个元素要么为 null 不同,您可以有 15 个具有相同类名的元素(并且可能是这样)。

Even if you got the elements by the class name via a document.getElementsByClassName or jQuery, you'd have to know which one you wanted (the first one, 15th one, etc.) to pick out a single element. This is why you see all the examples by ids.

即使您通过 document.getElementsByClassName 或 jQuery 通过类名获取元素,您也必须知道您想要哪个元素(第一个、第 15 个等)来挑选单个元素。这就是为什么您可以通过 id 看到所有示例。

回答by techfoobar

You can use getElementsByClassName which is now natively suported by most browsers.

您可以使用 getElementsByClassName 现在大多数浏览器都支持它。

See http://www.quirksmode.org/blog/archives/2008/05/getelementsbycl.html

http://www.quirksmode.org/blog/archives/2008/05/getelementsbycl.html