PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] How can i target appended items one by one in javascript?

 May 12, 2022     append, arrays, html, javascript, loops     No comments   

Issue

I created a simple new tab page similar to web browsers, but when I create a new tab and press the x icon to triger closetab() it closes all the tabs and does not delete them in order one by one. How do i make each of appended items unique?

JS:

function addTab() {
    
        var img = document.createElement("img");
        img.src = "resources/img/delete-icon.svg";
    
        img.className = 'deleteicon';
        img.id = "deletetab";
        img.onclick = closeTab;
    
        var ulLocation = document.getElementsByClassName('abc')[0];
        var whereTab = document.getElementById('listid');
    
        var addTab = document.createElement('li');
        addTab.className = 'first-tab';
        addTab.id = "listid";
    
        addTab.className = 'active';
      
        addTab.innerHTML = "mozilla-firefox/newtab";
        addTab.appendChild(img2);
    
        ulLocation.appendChild(addTab);
    
        addTab.appendChild(img);
    }

function closeTab() {
    var whereTab = document.getElementById('listid');
    if (whereTab.style.display == 'block') {
        whereTab.style.display = 'none';
    } else {
        whereTab.style.display = "none";
    }
}

Solution

You have at least 2 options. One is to target the active tab and close it when the X is clicked. This is assuming you only have one active tab at a time (denoted by an active class for example).

function closeTab(event) {
   document.querySelector('li.tab.active').remove();
}

Another option is to reference the tab relative to the close icon, which you can reference in the event argument of your click listener. Since you're adding these dynamically, you can just remove them with the delete click rather than hide. Something like:

function closeTab(event) {
   event.target.closest('li.tab').remove();
}

In these examples, you have set a className for your tab containers to be tab



Answered By - Kinglish
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing