Search code examples
javascriptmootoolselementmootools1.2

fetch HTML Element object using javascript, mootools


Please check my HTML below:

<table cellpadding="0" cellpadding="0" border="0">
    <tr>
        <td>
            <div class="toogler">Demo1</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="element">Demo1 Content</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="toogler">Demo1</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="element">Demo1 Content</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="toogler">Demo2</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="element">Demo2 Content</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="toogler">Demo3</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="element">Demo3 Content</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="toogler">Demo4</div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="element">Demo4 Content</div>
        </td>
    </tr>
</table>

Here is my JS Code:

<script type="text/javascript" language="javascript">
    $$('.toogler').each(function(e){
        alert(e);
        // this will alert all the toogler div object

    });
</script>

my problem is that how can i fetch the object of the next div with class element

if i have object of the first toogler then how can i get the object of the next first div which class 'element'

I don't want to give the ids to the elements


Solution

  • if you can't alter the html output and refactor as suggested by oskar (best case), this works:

    e.getParent().getParent().getNext().getFirst().getFirst() - it will return you the next div but it's slow.

    unfortunately, tables break .getNext("div.element") as it's not a sibling.

    another way that works is this (if their lengths match) - it will be MUCH faster if the reference is put in element storage as a 1-off:

    var tooglers = $$("div.toogler"), elements = $$("div.element");
    tooglers.each(function(el, i) {
        console.log(elements[i]);
        el.store("contentEl", elements[i]);
    });
    

    i don't like either solution though, not maintainable / scalable enough.