How to Get Element By Class in JavaScript?

前端 未结 11 2297
南旧
南旧 2020-11-22 01:48

I want to replace the contents within a html element so I\'m using the following function for that:

function ReplaceContentInContainer(id,content) {
   var c         


        
相关标签:
11条回答
  • 2020-11-22 02:13

    This code should work in all browsers.

    function replaceContentInContainer(matchClass, content) {
        var elems = document.getElementsByTagName('*'), i;
        for (i in elems) {
            if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
                    > -1) {
                elems[i].innerHTML = content;
            }
        }
    }
    

    The way it works is by looping through all of the elements in the document, and searching their class list for matchClass. If a match is found, the contents is replaced.

    jsFiddle Example, using Vanilla JS (i.e. no framework)

    0 讨论(0)
  • 2020-11-22 02:13

    jQuery handles this easy.

    let element = $(.myclass);
    element.html("Some string");
    

    It changes all the .myclass elements to that text.

    0 讨论(0)
  • 2020-11-22 02:16

    I assume this was not a valid option when this was originally asked, but you can now use document.getElementsByClassName('');. For example:

    var elements = document.getElementsByClassName(names); // or:
    var elements = rootElement.getElementsByClassName(names);
    

    See the MDN documentation for more.

    0 讨论(0)
  • 2020-11-22 02:18

    A Simple and an easy way

    var cusid_ele = document.getElementsByClassName('custid');
    for (var i = 0; i < cusid_ele.length; ++i) {
        var item = cusid_ele[i];  
        item.innerHTML = 'this is value';
    }
    
    0 讨论(0)
  • 2020-11-22 02:21
    document.querySelectorAll(".your_class_name_here");
    

    That will work in "modern" browsers that implement that method (IE8+).

    function ReplaceContentInContainer(selector, content) {
      var nodeList = document.querySelectorAll(selector);
      for (var i = 0, length = nodeList.length; i < length; i++) {
         nodeList[i].innerHTML = content;
      }
    }
    
    ReplaceContentInContainer(".theclass", "HELLO WORLD");
    

    If you want to provide support for older browsers, you could load a stand-alone selector engine like Sizzle (4KB mini+gzip) or Peppy (10K mini) and fall back to it if the native querySelector method is not found.

    Is it overkill to load a selector engine just so you can get elements with a certain class? Probably. However, the scripts aren't all that big and you will may find the selector engine useful in many other places in your script.

    0 讨论(0)
  • 2020-11-22 02:26

    var elems = document.querySelectorAll('.one');
    
    for (var i = 0; i < elems.length; i++) {
        elems[i].innerHTML = 'content';
    };

    0 讨论(0)
提交回复
热议问题