tnocs
tnocs

Reputation: 59

Adding only new list items to list

I'm fairly new to JavaScript, so looking for the simplest solution possible (also, not looking for a jQuery solution).

I'm trying to add clicked list items to a new list, only if the clicked list item isn't already in the new list. I have managed to add the clicked list item to the new list, but I fail to create a functioning if statement that checks the new list for the current item.

window.onload = function () {
    var ul = document.getElementById('bulk');

    ul.addEventListener('click', function (e) {
        var target = e.target;
        while (target && target.parentNode !== ul) {
            target = target.parentNode; 
            if(!target) { return; } 
        }
        if (target.tagName === 'LI'){
            var node = document.createElement("LI");
            var textnode = document.createTextNode(target.id);
            var textarea = document.getElementById("test1");
            if (!textarea.querySelector(target.id)) {
                node.appendChild(textnode);
                document.getElementById("test1").appendChild(node);
            }
        }
    });
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="test.js"></script>
    </head>

    <body>
        <ul id="bulk">
            <li id="banana"><a href="#"><b>banana</b></a></li>
            <li id="apple"><a href="#"><b>apple</b></a></li>
        </ul>
        <ul id="test1"></ul><br>
    </body>
</html>

Upvotes: 0

Views: 254

Answers (1)

AKX
AKX

Reputation: 168967

Since you're not supposed to have multiple elements with the same ID in a single document, I changed things so the unique ID of each element is in a dataset attribute data-id.

Beyond that, it's just a question of using querySelector() to figure out whether such a node already is in the destination list.

var ul = document.getElementById('bulk');
var destination = document.getElementById("test1");

ul.addEventListener('click', function(e) {
  var target = e.target;
  while (target && target.parentNode !== ul) {
    target = target.parentNode;
    if (!target) {
      return;
    }
  }
  if (target.tagName === 'LI') {
    var id = target.dataset.id;
    var node = document.createElement("LI");
    node.dataset.id = id;
    var textnode = document.createTextNode("element with id " + id);
    if (destination.querySelector("[data-id=" + id + "]")) {
      return;
    }
    node.appendChild(textnode);
    destination.appendChild(node);
  }
});
<ul id="bulk">
  <li data-id="banana"><a href="#"><b>banana</b></a></li>
  <li data-id="apple"><a href="#"><b>apple</b></a></li>
</ul>
<hr />
<ul id="test1">
</ul>

Upvotes: 1

Related Questions