1

I'm learning jQuery I still have some problems with DOM. I have one table that contains 3 rows and each row have 5 content. I need to add a forth row and its respective contents. Here's my code:

    <table>
      <tr>
        <td>content</td>
        <td>content</td>
        <td>content</td>
        <td>content</td>
      </tr>
    <table>

Above is the example How the table should be did Below is my jQuery code

    var arrayContent = ['Content1','Content2','Content3','Content4','Content5'];

    $('table').append(function(){
      return $('<tr>').append(function(){
         for(var i = 0; i < arrayContent.length; i++){
              return $('<td>')
         }
      })
    })

So this code abode only add one tag and I need to add more to my page. Does anyone know how I can improve or suggest new way to do this?

1
  • The quotes in arrayContent are incorrect. Commented Nov 22, 2015 at 21:17

2 Answers 2

1

// comments inline

var arrayContent = ['Content1','Content2','Content3','Content4','Content5'];

$('table').append(function(){
  return $('<tr>').append(function(){
    var td = '';  // create an empty string
    for(var i = 0; i < arrayContent.length; i++){
      td += '<td>' + arrayContent[i] + '</td>';  // compose the table data
    }
    return td;
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table></table>

Then, in your browser's web inspector, you will get:

enter image description here

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

3 Comments

@raul Why the td return was put out the loop? My thought was every return is to add a new td tag on the page. My logic was incorrect about this?
@ItaloLemos In your code, when you did return $('<td>'), the for loop doesnt go into the 2nd iteration since you are returning a value right there. However, In my code, I am returning it once all iterations are complete. :)
Yeah, make sense for me now. Thanks for share your knowledge. I appreciate .
1

Here's a slightly different approach:

var arrayContent = ['Content1','Content2','Content3','Content4','Content5'];

function foo() {
	var dom = '<tr>';
	for (var i = 0; i < arrayContent.length; ++i)
		dom += '<td>' + arrayContent[i] + '</td>';
	dom += '</tr>';
	$('table').append(dom);
}

window.onload = foo; // here you can call the function on other events too, e.g. onclick
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>

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.