0

I am currently trying to create divs dynamically with jquery. I have a function called createDivs that takes an array of x names. I would like to create a div for each name and assign the div the id=”new-name” that was passed in through the array. All dynamically created divs are appended to <div id=”main”></div>. However so far the divs are created but the names are placed in each div. How could I assign a single name per div and append to main?

function createDivs (divName) {
          for (var i=0, len=divName.length; i < len; i++) {
        $('#main').append('div').addClass('new-'+divName)
      }
}

call the function

createDivs(['navBar', 'footer', 'sidePanel', 'socialFeed']);

Current output

<div id="main">
<div id="new-" navBar,footer,sidePanel,socialFeed=""></div>
<div id="new-" navBar,footer,sidePanel,socialFeed=""></div>
<div id="new-" navBar,footer,sidePanel,socialFeed=""></div>
<div id="new-" navBar,footer,sidePanel,socialFeed=""></div>
</div>

Desired output

<div id="main">
<div id="navBar"></div> 
<div id="footer"></div> 
<div id="sidePanel"></div>
<div id="socialFeed"></div> 
</div>
0

1 Answer 1

2

Change:

$('#main').append('div').addClass('new-'+divName)

To

var $div = $("<div>", { id: divName[i] });
$('#main').append($div);
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfect. I see what i was doing wrong now. As mentioned above I was assigning the whole array to the div and just the element.

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.