BTK
BTK

Reputation: 99

How to add multiple divs with same name but with different content using jQuery

I would like to loop through the JSON array and create multiple <div>s with same class name "article" with different content like so:

<div class="article-list">
    <div class="article">
        <div class="article-name">Ford</div>
        <div class="article-models">Fiesta</div>
    </div>
    <div class="article">
        <div class="article-name">BMW</div>
        <div class="article-models">320</div>
    </div>
    <div class="article">
        <div class="article-name">Fiat</div>
        <div class="article-models">500</div>
    </div>
</div>

function test() {
  var data =  [
    { "name":"Ford", "models":"Fiesta" },
    { "name":"BMW", "models": "320"  },
    { "name":"Fiat", "models": "500" }
  ]
  
  data.forEach((obj)=> {
    
    $(".article-list").append(`<div class="article" />`)
    
    var text = ''    
    Object.keys(obj).forEach((key)=> {
      text += `<div class="article-${key}">${obj[key]}</div>`

    })
     
     $(`.article`).append(text)
     
  })
}

test()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="article-list"></div>

with above code, the first <div> gets created with all three values from the JSON array instead of just one. I'm not sure how to achieve this. Could anyone please tell me what needs to be fixed here?

Upvotes: 0

Views: 585

Answers (1)

ibrahimyilmaz
ibrahimyilmaz

Reputation: 2335

Because you are appending to divs with class '.article'. And it appends to all divs with this class. In your next iteration, there are two divs, and it's counting.

You can also do more refactor on here but when I just focus on your problem; here is editted snippet:

function test() {
  var data =  [
    { "name":"Ford", "models":"Fiesta" },
    { "name":"BMW", "models": "320"  },
    { "name":"Fiat", "models": "500" }
  ]
  
  data.forEach((obj)=> {
    var $article = $('<div class="article" />')
    
    var text = ''    
    Object.keys(obj).forEach((key)=> {
      text += `<div class="article-${key}">${obj[key]}</div>`

    })
     
     $article.append(text)
     
     $(".article-list").append($article)
  })
}

test()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="article-list"></div>

Upvotes: 1

Related Questions