1

I a have problem - I am showing in my html data from javascript, and i have to sort it after click. Here is my code:

const data = [
  {
    "id": 2,
    "title": "ASD",
    "src": "https://cloudfour.com/examples/img-currentsrc/images/kitten-small.png"
  },
  {
    "id": 1,
    "title": "FGH",
    "src": "https://cloudfour.com/examples/img-currentsrc/images/kitten-small.png"
  }
]
const info_container = document.querySelector('.info-container')

const sort = () => {
  data.sort((a, b) => parseFloat(a.id) - parseFloat(b.id))

  fetchData()
}

const fetchData = () => {
  data.forEach((item, index) => {
  const img = document.createElement("img");
  const title = document.createElement('h3')

  const node = document.createTextNode(item.src);
  const node_title = document.createTextNode(item.title)

  title.appendChild(node_title)
  img.src = item.src

  info_container.appendChild(title)
  info_container.appendChild(img);

})
}
window.onload = function() {
  fetchData()
}

HTML:

<div><button onclick="sort()">sort</button></div>
  <div class="info-container">    
</div>

plunker: http://plnkr.co/edit/Yjn4jaLN45pYJHFZBZLn?p=preview

Instead of updating my actual view, a new one is created, how to fix that?

Thanks for answers in advance!

6
  • you're not calling sort anywhere ... so, that's a thing Commented Apr 14, 2019 at 6:42
  • Look in plunker, i am calling sort onclick button in html Commented Apr 14, 2019 at 6:42
  • why should I look elsewhere? If you do call sort, then of course it adds to the data ... all you do is appendChild Commented Apr 14, 2019 at 6:43
  • i have already edit my question Commented Apr 14, 2019 at 6:43
  • 2
    remove the old content and then add the sorted content Commented Apr 14, 2019 at 6:43

2 Answers 2

3

You need to reset the contents of info_container each time fetchData is called:

const fetchData = () => {
  info_container.innerHTML = "";
  //Rest of the code
}

Modified Plunker

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

Comments

-1
  1. It is strange you don't release your info_container children number increases on each click event. You want to replace your info_container content with a new one, so your new content structure doesn't matter at first glance , you should write a function that does the job, checking that you could at least replace a string with an new one. With @jack Bashford reply you have a solution

  2. Second wording could help in a code, just minor remark thought, your fetchData is not fetching anything at all

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.