简体   繁体   中英

Assigning unique ID for HTML elements created with insertAdjacentHTML

I'm trying to create a simple page where you enter some text into an input field, and from there you simply press a submit button to create a html element from the input field value.

My code so far is

    function remover(e) {
    let elementWrapper = document.getElementById(`list-item-wrapper`);
    if (event.target === document.querySelector('.list-input') && event.target.checked) {
        setTimeout(() => {
            elementWrapper.remove();
        }, 1000);
    } else {
        return;
    }
}

function handleClick() {
    let elementCount = 0;
    let inputNode = document.querySelector('.input-field');
    let uEl = document.querySelector('.unordered-list');
    uEl.insertAdjacentHTML(
        'afterbegin',
        `<div id="list-item-wrapper ${elementCount++}">
        <input type="checkbox" class="list-input" name=${inputNode.value}>
            <label for="list-input">
                ${inputNode.value}
            </label>
        </div>`
    );
}

My problem is that the elementCount variable doesn't increment when the handleClick function is called.

I've tried using other methods than insertAdjacentHTML but I was unable to make it work without it as I still need a unique identifier.

Put the elementCount Variable outside the handleClick function, otherwise it can't be accessed from anywhere and will always be 0 when you call handleClick. Additionally you need to increment it first and then append it to the insert string.

let elementCount = 0;

function handleClick() {
     elementCount++;
     let inputNode = document.querySelector('.input-field');
     let uEl = document.querySelector('.unordered-list');
     uEl.insertAdjacentHTML(
        'afterbegin',
        `<div id="list-item-wrapper ${elementCount}">
        <input type="checkbox" class="list-input" name=${inputNode.value}>
            <label for="list-input">
                ${inputNode.value}
            </label>
        </div>`
     );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM