How to Get Element By Class in JavaScript?

Javascript

Javascript Problem Overview


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

function ReplaceContentInContainer(id,content) {
   var container = document.getElementById(id);
   container.innerHTML = content;
}

ReplaceContentInContainer('box','This is the replacement text');

<div id='box'></div>

The above works great but the problem is I have more than one html element on a page that I want to replace the contents of. So I can't use ids but classes instead. I have been told that javascript does not support any type of inbuilt get element by class function. So how can the above code be revised to make it work with classes instead of ids?

P.S. I don't want to use jQuery for this.

Javascript Solutions


Solution 1 - Javascript

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)

Solution 2 - Javascript

Of course, all modern browsers now support the following simpler way:

var elements = document.getElementsByClassName('someClass');

but be warned it doesn't work with IE8 or before. See http://caniuse.com/getelementsbyclassname

Also, not all browsers will return a pure NodeList like they're supposed to.

You're probably still better off using your favorite cross-browser library.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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';
}

Solution 5 - Javascript

I'm surprised there are no answers using Regular Expressions. This is pretty much Andrew's answer, using RegExp.test instead of String.indexOf, since it seems to perform better for multiple operations, according to jsPerf tests.
It also seems to be supported on IE6.

function replaceContentInContainer(matchClass, content) {
    var re = new RegExp("(?:^|\\s)" + matchClass + "(?!\\S)"),
        elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if (re.test(elems[i].className)) {
            elems[i].innerHTML = content;
        }
    }
}

replaceContentInContainer("box", "This is the replacement text.");

If you look for the same class(es) frequently, you can further improve it by storing the (precompiled) regular expressions elsewhere, and passing them directly to the function, instead of a string.

function replaceContentInContainer(reClass, content) {
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if (reClass.test(elems[i].className)) {
            elems[i].innerHTML = content;
        }
    }
}

var reBox = /(?:^|\s)box(?!\S)/;
replaceContentInContainer(reBox, "This is the replacement text.");

Solution 6 - Javascript

This should work in pretty much any browser...

function getByClass (className, parent) {
  parent || (parent=document);
  var descendants=parent.getElementsByTagName('*'), i=-1, e, result=[];
  while (e=descendants[++i]) {
    ((' '+(e['class']||e.className)+' ').indexOf(' '+className+' ') > -1) && result.push(e);
  }
  return result;
}

You should be able to use it like this:

function replaceInClass (className, content) {
  var nodes = getByClass(className), i=-1, node;
  while (node=nodes[++i]) node.innerHTML = content;
}

Solution 7 - Javascript

var elems = document.querySelectorAll('.one');

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

There are 3 different ways to get elements by class in javascript. But here for your query as you have multiple elements with the same class names you can use 2 methods:

  1. getElementsByClassName Method - It returns all the elements with the specified class present in the document or within the parent element which called it.

    function ReplaceContentInContainer(className, content) {
        var containers = document.getElementsByClassName(className);
        for (let i = 0; i < containers.length; i++) {
            containers[i].innerHTML = content;
        }
    }
    ReplaceContentInContainer('box', 'This is the replacement text');
    
    <div class='box'></div>
    
  2. querySelectorAll Method - It select element on the basic of CSS selectors. Pass your CSS class to it with a dot and it will return all the element having specified class as an array-like object.

    function ReplaceContentInContainer(className, content) {
        var containers = document.querySelectorAll(`.${className}`);
        for (let i = 0; i < containers.length; i++) {
            containers[i].innerHTML = content;
        }
    }
    ReplaceContentInContainer('box', 'This is the replacement text');
    
    <div class='box'></div>
    

Solution 10 - Javascript

I think something like:

function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
    if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
        elems[i].innerHTML = content;
    }
}
}

would work

Solution 11 - Javascript

jQuery handles this easy.

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

It changes all the .myclass elements to that text.

Solution 12 - Javascript

When some elements lack ID, I use jQuery like this:

$(document).ready(function()
{
    $('.myclass').attr('id', 'myid');
});

This might be a strange solution, but maybe someone find it useful.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTaylorView Question on Stackoverflow
Solution 1 - JavascriptRandy the DevView Answer on Stackoverflow
Solution 2 - JavascriptColdColdView Answer on Stackoverflow
Solution 3 - JavascriptCristian SanchezView Answer on Stackoverflow
Solution 4 - JavascriptktaView Answer on Stackoverflow
Solution 5 - JavascriptafsantosView Answer on Stackoverflow
Solution 6 - JavascriptDagg NabbitView Answer on Stackoverflow
Solution 7 - JavascriptRoger CaustoView Answer on Stackoverflow
Solution 8 - JavascriptthornjadView Answer on Stackoverflow
Solution 9 - JavascriptSatish Chandra GuptaView Answer on Stackoverflow
Solution 10 - JavascriptKeatsKelleherView Answer on Stackoverflow
Solution 11 - JavascriptDaniel HøifødtView Answer on Stackoverflow
Solution 12 - JavascriptThe KrotekView Answer on Stackoverflow