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>
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.
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.