1

I am trying to parse JSON data into specific iterations of a class name "slide_content"

To get something like this:

slide_content[0]

But JS doesn't provide a getElementByClass() selector.

The API data in question is here: Converting Straight JS to JQuery

Cheers! Myles

Community
  • 1
  • 1
Myles Gray
  • 8,711
  • 7
  • 48
  • 70
  • Well "id" values really need to be unique throughout the document. Therefore, as you dynamically add content, you should either not give the elements "id" values (using "class" values instead), or else synthesize unique "id" values as you go. – Pointy Jan 24 '11 at 18:34
  • If I give them class values then I cannot target them directly as for some bizarre reason JS supports getElementByID but not getElementByClass... I need them to all have the same class in order for the tab slider to function, thus meaning usage of class names, but then class names are not targetable via a JS API. – Myles Gray Jan 24 '11 at 18:37

2 Answers2

2

Newer browsers (IE9 and above) have support for document.getElementsByClassName (which ironically means that it has less support than querySelectorAll, but I digress...), but that probably won't meet your compatibility needs. In this case, you can use something like this to get an Array of nodes with the class.

var nodes = document.getElementsByTagName('*'),
    targetClass = 'myclass',
    result = [];

for(var i = 0, l = nodes.length; i < l; i++){
    if((nodes[i].className + ' ').indexOf(targetClass + ' ') !== -1){
        result.push(nodes[i]);
    }
}

This is not an exact duplicate of getElementsByClassName, since that function returns a NodeList, but it should be close enough for most purposes.

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
1

Use jQuery. It allows you to use $('.someClass') to retrieve all elements with a given class name.

If you cannot use jQuery or another JS library for some reason, simply use the Sizzle selector engine which is also used by jQuery - it's not very much code so you could even copy&paste it into one of your project's JS files (but don't do that, it's ugly :p). But since you tagged your question with jquery I assume you can use jQuery...

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Thanks ThiefMaster - Yes JQuery is most defiantly an option, I will need to work on JQueryifying the code then... – Myles Gray Jan 25 '11 at 14:25