How to Get Element By Class in JavaScript?

前端 未结 11 2347
南旧
南旧 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: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.

提交回复
热议问题