1

I'm a JQuery Newbie. I'm trying to append an object property( declared in an array form) to an html element like the following

HTML:

<div id="container">
<p>some text </p>
<p>some text </p>
<p>some text </p>
</div>

JQuery Script:

var obj{
property  :  {'apple', 'orange', 'banana'}
}

for(i=0; i<=2; i++){
$("#container p:eq("+i+")").append(obj.property[i]);
}

and hope to get this:

<p>some text apple</p>
<p>some text orange</p>
<p>some text banana</p>

There are no appending shown at all, though my Firebug console shows no error report.

What am I doing wrong? Also, is there any way to replace the for loop with .each(), if it's a better practice?

Thank you

2 Answers 2

6

Your list of properties isn't correctly formed. A numerically indexed list literal is formed using square brackets, not curly brackets.

The code you posted should be giving you a syntax error. If it's not, it's possible that it's simply not getting executed at all.

Here's a fixed up version:


  var obj = {
    property  :  ['apple', 'orange', 'banana'] 
  }

  for(i=0; i<=2; i++){
    $("#container p:eq("+i+")").append(obj.property[i]);
  }

Sign up to request clarification or add additional context in comments.

Comments

1

As stated in another answer, obj should be defined as such:

var obj = {
  property : ['apple', 'orange', 'banana']
}

The for loop will work, but it seems better practice to use .each(), if for no other reason just because you don't have to hard-code the values -- if you use for, then if you ever change the number of properties, you'll have to go update that loop too. Here is how I would do it:

$("#container > p").each(function(i) { $(this).append(obj.property[i]); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.