0

I have a list of elements where I want to create list like structure with the Bootstrap element (example):

<div class="list-group">
  <a href="#" class="list-group-item active">
    <h4 class="list-group-item-heading">List group item heading</h4>
    <p class="list-group-item-text">...</p>
  </a>
</div>

I figured that I will do something like:

foreach(element)
{
   $("#ul").append($("<a href='" + element +"'>").text(element));
}


<div class="container">
  <div id="ul" class="list-group">
</div>

This works fine but I am not sure how to do the other nested elements (<h4> and <p>) and also set their text property. Also is there a cleaner way to do the href part of <a> element ? Any hints and tips are appreciated.

Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169

2 Answers2

3

You need to build those elements individually and append them after you've already operated on them:

foreach(element)
{
  var anchor = $("<a href='" + element +"'>");
  var header = $('<h4>').text('stuff');
  var p = $('<p>').text('More stuff');
  anchor.append(header).append(p);
  $("#ul").append(anchor);
}
Brennan
  • 5,632
  • 2
  • 17
  • 24
1

As far as the main question goes, Brennan's answer will definitely do the trick. As for another way to do the href in your <a>, check out this post.

Community
  • 1
  • 1
WillFole
  • 11
  • 3