jquery find issue with counting children elements

In the following code the div:first class name is create.so the code actually appends one more div to id accordion but when i do a console.log() to find the number of .create elements it always prints 1 what am i doing wrong

var div = $("#accordion").find("div:first").html();
arr=2;
for(var i=0;i<arr.length-1;i++)
{
    $("#accordion").append(div);
}

console.log($("#accordion").find(".create")) //always print 1

$("#accordion").children(".create").each(function(index) {
    console.log("==") //prints only once
});

EDIT

arr.length is not the issue for me..when i print $("#accordion").html() i see two divs with .create but cannot count it or get it in the each loop

Answers


The problem could be that since you are using .html() to create div, it gets the inner contents of the first div, not the child itself.

You need to use clone() here

var div = $("#accordion").find("div:first");
arr=2;
for(var i=0;i<arr.length;i++)
{
    $("#accordion").append(div.clone());
}

console.log($("#accordion").find(".create")) //always print 1

$("#accordion").children(".create").each(function(index) {
    console.log("==") //prints only once
});

You never go into your loop because of arr.length. I believe you meant i<arr-1.


Use following

var div = $("#accordion").find("div:first").html();
arr=2;
for(var i=0;i<arr-1;i++)
{
    $("#accordion").append(div);
}

console.log($("#accordion").find(".create")) //always print 1

$("#accordion").children(".create").each(function(index) {
    console.log("==") //prints only once
});

It should work. Actually arr has value 2 and you were using arr.length-1. It will always return 0.


Need Your Help

How to override DbContext.Seed() when using the Visual Studio Model Designer

visual-studio-2012 entity-framework-5 entity-framework-designer

I just started to play around with EntityFramework. In VS2012 I can use the designer which nicely creates all the boilerplate code. However, I am now at a point where I wanted to start playing with

Creating a UISwitch Programmatically

iphone objective-c uiview uiswitch

In a seemingly never ending effort to learn more about iphone development, I have been playing around with some of the source code available through apples developer website. The particular example...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.