RemoveChild (); удаляет два входа? Мне просто нужно удалить 1 вход - PullRequest
0 голосов
/ 11 июля 2020

Я новичок в javascript, и в настоящее время мне нужна отдельная функция удаления. Я решил использовать variable.removeChild(), но он удаляет 2 входа

document.addEventListener('DOMContentLoaded', () => {

  document.getElementById("delete").addEventListener("click", function deletes(){
        
    var parent = document.getElementById("list");
        
    var child = parent.getElementsByTagName("li")[0];
        
    console.log(child);
        
    parent.removeChild(child); //deletes a pair of my li inputs
        
    
  });

});

Вот как выглядит мой код HTML

<body>
        <h1>LIST</h1>
        <h2>Items: </h2>
        <div>
            <ol id="list">
                <li>test</li>
            </ol>
        </div>
        <form id="insert">
            <input type="text" id="itemInput" placeholder="Item" name="item">
            <input type="submit" id="add" value="Add">
                
        </form>
        <input type="submit" id="search" value="Search"> //search doesn't do anything yet
        <input type="submit" id="delete" value="Delete first item">  //Here is where it begins

    </body>

Вот моя другая функция. Я также использую addEventListener (), возможно, в этом проблема? Этот код позволяет мне динамически добавлять элементы списка по желанию пользователя

document.addEventListener('DOMContentLoaded', () => {
//calls function once #insert has submit a form/hit the input 
document.querySelector('#insert').onsubmit = () => {

    //create variable
    if(document.querySelectorAll('li').length >= 10){
        return false;
    };

    //get the value of the input
    let name = document.querySelector('#itemInput').value;
    //stores value in the h3 tag


    //create element of 'li'
    const li = document.createElement('li');
    //add the contents to the value of 'name'
    li.innerHTML = name;

    //now append the element to the #list section
    document.querySelector('#list').append(li);

    //gets the length of all the list items (li) and stored it in counter
    counter = document.querySelectorAll('li').length;
    //change the h2 tag with the updated list items
    document.querySelector('h2').innerHTML = `Items: ${counter}`;

    //prevents the form from submitting (good for debugging!!!)
    return false;
};

});

1 Ответ

0 голосов
/ 11 июля 2020

Получите список с document.querySelector('#list') и первым li, добавив .querySelectorAll('li')[0], затем найдите входные данные внутри.

document.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#delete').addEventListener("click", function deletes(){
        let li = document.querySelector('#list').querySelectorAll('li')[0];
        let inputs = li.querySelectorAll('input');
        // Is there any input in li?
        if(inputs.length > 0) {
            // Delete only the first one
            inputs[0].remove();
            // If you want to keep other inputs, just disable the button
            this.disabled = true;
        }
    });
});
<ul id="list">
  <li>
     <input type="text" value="input1">
     <input type="text" value="input2">
  </li>
</ul>
<button id="delete">Delete</button>

querySelector () и querySelectorAll () позволяют находить элементы по идентификатору, имени класса, тэгу, атрибутам и т. Д. c. Как и jQuery. Артикул: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...