tags:

views:

164

answers:

5

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 abaove 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.

A: 
document.querySelectorAll(".class");

That will work in "modern" browsers that implement that method.

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.

CD Sanchez
this doesn't work in any of the IE's unfortunately.
Taylor
@Taylor: I think it works in IE8 (not 100% sure - too lazy to google it). Regardless, I added some info regarding backwards compatibility using third party selector engines.
CD Sanchez
A: 

No jquery, but how about YUI?!

If you don't, you'll need to roll your own which might include;

  • Effeciently narrowing down element checking
  • Checking the className property of elements found in the above checking, remember that you'll need to roll your own check to handle multiple class names, ie; class="class1 class2".

d

EDIT: Daniel's right, but I was assuming 'all browsers' catered for.

Danjah
A: 

I think something like:

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

would work

akellehe
if you have only a handful of elements in your page, otherwise this is O(N) solution
larson4
I wasn't the one which down voted you, but there's a couple of bugs, first is that you need to get the `className` `getAttribute('class')` doesn't work in all browsers, other is that it won't work for elements with multiple selectors. +1 for trying.
Andrew Dunn
getAttribute('class') seems to work in all but IE, then getAttribute('className') works in IE
akellehe
A: 

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;
}
no
+3  A: 

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

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

Andrew Dunn
+1 - Good catch with the spaces, I always forget to do that... going to steal that for my answer ;) class is a reserved word in javascript though; you shouldn't use it for a variable name even though it really doesn't do any harm (yet).
no
I can't seem to get this to work with the function I was using. Could you please implement this with the ReplaceContentInContainer() function in my question. Sorry I'm a designer :p
Taylor
`class` isn't a reserved word in the current version of JavaScript duly noted though I'll edit in a sec, @Taylor, make sure you are passing a class to the function, not an id.
Andrew Dunn
@no with that function you don't have to have any content inside the element you want to replace. You can have a string in there or you can have it empty. Either way the replacement text will suddenly appear there when the function is called.
Taylor
@Andrew Dunn dude you rock, I got it to work and it actually works even in IE6, thanks a lot!
Taylor
Andrew, @no - Using `class` as a variable name does not work in Safari, so it does currently have an impact.
patrick dw
@Andrew Dunn -- see ES3 section 7.5.3, "Future Reserved Words" ... it's in there (and it's reserved now, not just in the future; it's just a silly section title).
no