Search code examples
javascriptdomprototypejs

Prototype.js get text from an element


I'm new to Protoype.JS and just testing it a bit because I heard it was good, but I'm stuck quite quickly. As easy as this is with jQuery, it seems to be the end of the world to get the text in an element. I've tried innerHTML in multiple ways but the only thing I can get is "undefined".

alert($$('.mnu_item').innerHTML);
alert($('content').innerHTML);

None of these work. Content is a div with id "content" and .mnu_item is an anchor tag with class ".mnu_item". I don't get what the problem is, probably something stupid but it would be great if somebody could point me in the right direction!

EDIT: I've found that it isn't the innerHTML that doesn't work but it's the class selector. The second line in the code above does work. How can I select an element by its class in the latest Prototype version if this isn't the correct way?


Solution

  • Has the DOM loaded when you run your script? If you're not running this code in a window.onload or by placing it at the end of the body, then the elements by not exist when it runs.

    Try placing your script just inside the closing </body> tag.

    <body>
        <!-- my content -->
    
        <script type="text/javascript">
            alert($('content').innerHTML);
        </script>
    </body>
    

    Also, your first line is selecting correctly, but will return an Array of elements, so innerHTML will be undefined.

    To iterate the Array, you can do this:

    $$('.mnu_item').each(function(val,i) {
        alert(val.innerHTML);
    });
    

    or if you want to end up with an Array of the innerHTML values, do this:

    var values = $$('.mnu_item').map(function(val,i) {
        return val.innerHTML;
    });