简体   繁体   中英

How to use innerHTML with class

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.

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

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

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.

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

/*
  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.

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

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

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

Edit: Here's an example

First, your Javascript function:

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

Some sample 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. 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).

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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