JS Prototype get element by class?

FLX picture FLX · Mar 9, 2011 · Viewed 36.8k times · Source

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!

Answer

bwest picture bwest · Mar 9, 2011

Use a css selector in prototype.

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

jsfiddle