0

I am trying to destroy elements on page load.

Here is my jQuery:

<script type="text/javascript">
    var amount = 0;
$('li.<?php echo $username ;?>').each(function() {
    amount++
    if (amount > 1) {

        $(this).destroy();
    }
});

</script>

For some reason .destory does not work. I am limiting the list items to 1, but the above will still generate all list items.

I have got around this by using .remove. The only problem is, there are thousands of elements to load, and are still loading in the dom. This is causing very long loading times.

Any ideas on what else i could try?

Cheers, Dan

danyo
  • 5,686
  • 20
  • 59
  • 119

3 Answers3

1

First, you should use remove(), instead of destroy. Then it depends where you have included the script. If you have included it in the head of your HTML you need to wait for the DOM to be ready, using $(document).ready(..) like so:

<script type="text/javascript">
  $(document).ready(function(){
    var amount = 0;
    $('li.foo').each(function() {
      amount++
      if (amount > 1) {
        $(this).remove();
      }
    });
  })
</script>
  • although it still loads the list items... but it does remove them after page load – danyo Jun 06 '13 at 08:14
  • `destroy()` just add an attribute `_destroy:true` to the element like a flag, that way you will know exactly what has been removed, but if you want the element to disappear then use `remove()` – Eli Oct 29 '13 at 11:37
0

try this

$(this).remove();

instead of destroy

PSR
  • 39,804
  • 41
  • 111
  • 151
  • as mentioned above, i am using .remove. This does not stop the elements from loading in the dom. – danyo Jun 06 '13 at 08:07
0

Instead of amount++ you should use :first in your selector.

For example $('li.<?php echo $username ;?>:not(:first)')

I think instead of removing each element individually you should try removing their parent only because if you remove parent then all of it's children will be removed automatically.

Try to remove ul instead of each element individually.

Now if you don't want to remove first element then you clone it in some variable by using http://api.jquery.com/clone/ and then after removing parent ul you can again create ul and then insert the cloned li into it.

Removing parent will be much more efficient than removing each child individually.

Jahanzeb
  • 613
  • 4
  • 11