Search code examples
mootools

How to remove hyperlink using mootools based on its value?


In the code below how to remove the li based on the value of hyperlink?

<ul class="clean menu sub">
    <li>
        <a cat="tech" class="sec_net_1" href="javascript:void(0);" name="&amp;lid=choose_category_internet_fios" rel="1">FiOS Internet</a>
    </li>
    <li>
        <a cat="tech" class="sec_net_1" href="javascript:void(0);" name="&amp;lid=choose_category_internet_hsi" rel="1">High Speed Internet</a>
    </li>
    <li class="last" style="margin-bottom:7px;">
        <a cat="tech" class="sec_net_1" href="javascript:void(0);" name="&amp;lid=choose_category_internet_dialup" rel="1">Dial-up</a>
    </li>
</ul>

I get the valu of the hyperlink in a variable. Now based on the value other 2 li's should be deleted. How can we achieve this using mootools?

Now if I get flag="Dial-up", Other 2 li's should be deleted and the code should look like this:

<ul class="clean menu sub">
    <li class="last" style="margin-bottom:7px;">
        <a cat="tech" class="sec_net_1" href="javascript:void(0);" name="&amp;lid=choose_category_internet_dialup" rel="1">Dial-up</a>
    </li>
</ul>

Here I get the value of Flag from server.


Solution

  • If you can leverage on link names the solution is a single line:

    http://jsfiddle.net/5axJc/

    $$("ul.menu :not(a[name='&li=choose_category_internet_dialup']) !> li").destroy()
    

    calling destroy on a collection (I would have used document.getElements in production code) will call your method on every elements in it.

    In the selection expression there are several esoteric selector and maybe it worth some deeper explanation:

    • ul.menu is a plain class based selector
    • :not(a[name='&li=choose_category_internet_dialup'])
      select links based on the name attributes that do :not() match the value
    • !> is a parent selector

    hence you can read the selector as:

    select all the li into the menu ul that are father of an anchor whose name is NOT your desired value.

    EDIT

    To select only the li that are parents of the searched one just select it with ul.sub a[name='&lid=choose_category_internet_fios'] !> li and based on that select all siblings with ~ li. the result is like this.

    $$("ul.sub a[name='&lid=choose_category_internet_fios'] !> li ~ li").dispose()
    

    Note we have get rid of the :not() selector. To me it is a more linear way to accomplish the task.