Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Prototype get element by class?

I got the following code and I'm trying to make it match on a class instead of on an id:

Html:

<div id='testdiv'>
    <div class="lol">
        [First Title|<a class="external" href="http://test.com">http://test.com</a>]
        Another line
        [Second Title|<a class="external" href="http://test.com">http://test.com</a>]
        More text
        [Third Title|<a class="external" href="http://test.com">http://test.com</a>]
    </div>
</div>

Javascript:

var textContainer = document.getElementById("testdiv");
var linkText = textContainer.innerHTML;
var pattern = /\[([^|]+)\|([^>]+.?)[^<]*(<\/a>)\]/g;
var result = linkText.replace(pattern, "$2$1$3");

textContainer.innerHTML = result;

Full example: http://jsfiddle.net/JFC72/17/

How can I make it match on "myclass" instead? Thanks!

like image 731
FLX Avatar asked Mar 09 '11 18:03

FLX


3 Answers

Use a css selector in prototype.

var textContainer = $$('div.myclass')[0];

jsfiddle

like image 106
bwest Avatar answered Oct 12 '22 03:10

bwest


I think you need the $$ method. It selects DOM elements that match a CSS selector strict. In this case you want

var elements = $$('.myclass');

It returns a list of all matching elements in document order. You can access them by index or operating on all of them with things like each

http://www.prototypejs.org/api/utility

This is what Prototype is about. getElementById is oooold

like image 24
jon_darkstar Avatar answered Oct 12 '22 04:10

jon_darkstar


Here is a working example of how you would use each in Prototype to loop through all elements with a class of order-cc-charged.

var order_cc_charged = 0;

$$('order-cc-charged').each(function (elem) {
   order_cc_charged += parseFloat($('order-cc-charged').innerHTML);
});
like image 3
crmpicco Avatar answered Oct 12 '22 02:10

crmpicco