Ityka Bandta
Ityka Bandta

Reputation: 105

Set an element after a dynamically appended json key inside the dom using Jquery

I have a json as follows -

const data = [{
  "testData": {
    "one": "1",
    "two": "2",
    "three": "three"
  }
}]

I am setting the key value pair after a certain div as follows-

$.getJSON("json-file.json",
function (data) {
  const json = data.testData;
  for (const key in json) {
    var listItem = `<div><p>${key}</p><p>${json[key]}</p></div>`;
    $("#selectordiv").after(listItem);
  }
}

I want to set a p tag after the key "two" in the dom. I am doing something like -

$.getJSON("json-file.json",
function (data) {
  const json = data.testData;
  for (const key in json) {
    var listItem = `<div><p>${key}</p><p>${json[key]}</p></div>`;
    $("#selectordiv").after(listItem);
    if(key == "two"){
      $('this').after("<p>test</p>");
    })
  }      
  })

This give me an error. How can I achieve this?

Upvotes: 0

Views: 50

Answers (1)

Greedo
Greedo

Reputation: 3559

There are so many syntax error in this snippet.. you can solve them just by executing the code in the console :)

Here is a solution:

const data = [{
  "testData": {
    "one": "1",
    "two": "2",
    "three": "three"
  }
}]

function compile(data) {
  const json = data[0].testData;
  for (const key in json) {
    var listItem = `<div><p>${key}</p><p>${json[key]}</p></div>`;
    $("#selectordiv").append(listItem);
    if(key == "two"){
      $("#selectordiv").append("<p>test</p>");
    }
 }      
}

compile(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="selectordiv"></div>

Upvotes: 1

Related Questions