views:

45

answers:

3

Hello,

I have an HTML web page full of divs and span tags identified with class that have lots of data I need in other format. I was wondering what would be the best way to do this with javascript.

Thank you for the help.

+3  A: 

The fastest way? jQuery:

$(".myClass").each(function() {
    // work with your data here
});
Chris Pebble
it may be the shortest way but not the fastest...
galambalazs
Depends on if you're optimizing for CPU cycles or developer cycles :). It's probably the fastest to implement, but you're right, it may not be the most efficient way.
Chris Pebble
Is it that slow?
Reonarudo
Not at all. We're engaging in micro-optimization theater at this point. I would recommend trying the above first, and if you need to squeeze an additional millisecond or two out of your code, looking at native javascript/dom methods.
Chris Pebble
A: 

More lowlevel, but should be a lot faster (a lot less overhead):

var myelements = document.evaluate('//div[@class=myClass"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < myelements.snapshotLength; i++) {
  var dataElement = myelements.snapshotItem(i);
  // work with your data here
}

(ok, you'd have to do it twice (once for div and once for span), it's more code and doesn't look as nice, but it should still be faster)

Alex
A: 

If you are wanting to get at all of the documents with a specific class then you will need to test for the presence of that class on each object. You will want to use a

document.getElementByTagName("*") // This should select everything

and loop through them to detect the proper name.

if (regex test == true) {
    // you found an element that matches
    // do what you will with it.
} 

If you find the elements you need do what you need with them. Now you have processed all elements on the page and found elements that match your criteria. Good luck.

John
I have read that regex and HTML are a forbidden union under the heavens... So what kind of regex would this be?
Reonarudo
You would have to use a regular expression for searching through a classname. You can have multiple appended classnames in the same attribute. (ex class="this that orAnother"; if (className == "this"){} would not work as the full string is "this that orAnother".
John