Loop through ajax response?

Hi,

Im getting a response with a bunch of elements from the server, each has one of three classes. I want to append each into different containers depending on what class they have, but I’m not successful. Can anyone help me?

                   $('#one').append(response);
	        $('li').each(function(){
	        	if($(this).hasClass('.one')){
	        		$(this).appendTo('#one');
	        	} else if($(this).hasClass('.two')){
					$(this).appendTo('#two');
	        	} else {
	        		$(this).appendTo('#three');
	        	}

The code seems right. What happens differently when you run this code? Are all elements being appended to the element with id of three? Maybe try removing the dot from .hasClass('.one') and .hasClass(.two). Classes in Javascript are written without the dot so for instance that first $(this).hasClass('.one') will evaluate false even though the one class is there.

 $('#one').append(response);
    $('li').each(function(){
    if($(this).hasClass('one')){
      $(this).appendTo('#one');
    } else if($(this).hasClass('two')){
      $(this).appendTo('#two');
    } else {
      $(this).appendTo('#three');
    }
1 Like

yeah im stupid didnt notice the dots. however i did a filter on the response instead… like $(response).filter(‘.one’) … etc.

Sorry, what I said wasn’t entirely true. Some jQuery methods allow an htmlString as its parameters. Check it out:
http://api.jquery.com/appendto/

htmlString is used to designate a string that represents one or more DOM elements. In that case, appendTo('#one') uses #one to select the DOM element with such ID.

Can be done simpler without the loops and conditions.

$lis = $(response);
$lis.filter('.one').appendTo('#one');
$lis.filter('.two').appendTo('#two');
$lis.filter('.three').appendTo('#three');

filter returns a subset of the array that match a selector.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.