Home > database >  JavaScript/JQuery Appending DIVs with Corresponding Text (from List of Links)
JavaScript/JQuery Appending DIVs with Corresponding Text (from List of Links)

Time:11-06

When clicking on a link, I need to create a div with the text of that link. I've managed to do this for just the first object in my list, but not for all the rest of the items within the list element.

This is the snippet which creates a new div with the text of the element clicked. I thought it would work for each of my list elements. How can I make it work for an item that was just clicked? Is it possible to accomplish this without manually assigning unique IDs?

    var source;
  source = document.getElementById("source");
$(source).on("click", function () {
  $("#feed-grid").append($('<div >'   source.innerHTML   "</div>"));
});

https://codepen.io/sosophia10/pen/LYrZvgW

In this Codepen example, you'll see that clicking on the first item in the list, "Adele", adds a div to the grid with "Adele" as text. I need it to specifically reference the list item which was clicked, rather than just the first element with the source ID.

CodePudding user response:

You need to give the same class to all your links, then the js you can use is :

links = document.getElementsByClassName("link");
Array.prototype.forEach.call(links, function(element) {
   element.addEventListener("click", ()=> {
       document.getElementById("feed-grid").innerHTML  = 
       `<div >${element.text}</div>`;
   });
});

The codepen edited: https://codepen.io/orfeo59/pen/wvXzGqL

I hope it help you.

  • Related