简体   繁体   English

如何在类中使用innerHTML

[英]How to use innerHTML with class

I want to use innerHTML with the class as reference. 我想将innerHTML与该类一起用作参考。 I found lot of examples with id as reference. 我找到了很多ID为参考的示例。 Do anyone have any idea of how to get the innerHTML of the element without using the id name. 没有人知道如何在不使用id名称的情况下获取元素的innerHTML。

Please not that i don't want to use any JavaScript libraries like jquery here. 请不要,我不想在这里使用任何JavaScript库,例如jquery。

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;

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或某些库,因为它可以处理较旧的浏览器。

You can use document.getElementsByClassName, but that will not work pre-IE9. 您可以使用document.getElementsByClassName,但这在IE9之前不起作用。 Use this method from a Google Code project , I'm copy-pasting it here 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. 使用“ info-links”类获取文档中的所有元素。

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. 单击页面上的按钮,它将获取值。

The reason id is used is because IDs are unique: class names are not. 使用id的原因是因为ID是唯一的:类名不是唯一的。 In the text of your question you ask how to get the innerHTML of 'the element', but this could be incorrect. 在问题文本中,您询问如何获取“元素”的innerHTML,但这可能是错误的。 Unlike ids which will either be a single element or null, you could have 15 elements with the same class name (and likely do). 与可能是单个元素或null的id不同,您可以有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. 即使您通过document.getElementsByClassName或jQuery通过类名获得了元素,您也必须知道要选择哪个元素(第一个,第15个,等等)。 This is why you see all the examples by ids. 这就是为什么您通过id查看所有示例的原因。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM