How to loop through a clone list using jquery

Go To StackoverFlow.com

1

How do I loop through a clone list using jquery?

     <ul id=testList>
          <li><p> Test A </p></li>
          <li><p> Test B </p></li>
          <li><p> Test C </p></li>
          <li><p> Test D </p></li>
          <li><p> Test E </p></li>
     </ul>

jquery code...

         var $cloneList = $("#testList").clone();

         $cloneList.each(function()
         {
              alert($(this).html());
         });

The problem is the output of the alert method displays the content of the list:

             <p> Test A </p>

What I need is the display of the ul list like this

            <li><p> Test A </p></li>
2012-04-05 01:12
by Joseph Walker
works for me hmm - COLD TOLD 2012-04-05 01:20


0

Well what you're trying to iterate is a list of li elements. Each of which contains some html ("<p>text</p>").

The quickest way is to use outerHTML given the scenario you described:

$cloneList.find('li').each(function(){
alert(this.outerHTML);
});

However it might be prudent to post a larger scope of the problem since it appears that perhaps the result of .clone() is not exactly what you're wanting to work with.

2012-04-05 01:18
by itsallkizza
I'm sending the clone list through an ajax call to the server - Joseph Walker 2012-04-05 01:26


0

There's no direct way to print an element along with its own tag in jQuery, what you can do is to intermediately wrap an element in a div and print the innerHtml of it:

$clonseList.each(function() {
   alert(this.outerHTML || $('<div />').append($(this).clone()).html());
});

The above won't modify the DOM since we never append the extra <div> to the document.

2012-04-05 01:17
by Andreas Wong
Ads