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.
This code should work in all browsers.
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)
When some elements lack ID, I use jQuery like this:
This might be a strange solution, but maybe someone find it useful.
That will work in "modern" browsers that implement that method (IE8+).
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.
I'm surprised there are no answers using Regular Expressions. This is pretty much Andrew's answer, using
RegExp.test
instead ofString.indexOf
, since it seems to perform better for multiple operations, according to jsPerf tests.It also seems to be supported on IE6.
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.
A Simple and an easy way
Of course, all modern browsers now support the following simpler way:
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.