Home > Blockchain >  Why can I not manipulate an HTML button append to the DOM?
Why can I not manipulate an HTML button append to the DOM?

Time:11-03

Within my Javascript code, I am trying to append a button to the DOM. Upon appending all of my other elements, I can console.log them out and manipulate them; except for my submit button. Any insight into my issue is appreciated.

** HTML**

<html>
<head></head>
<body>
    <button id="new-character-btn">New Character</button>
    <div id="character-parent">
            <div id="character-div"></div>
    </div>
</body>
<script src="copy.js"></script>
</html>

Javascript

let newCharacterBtn= document.querySelector("#new-character-btn");
console.log(newCharacterBtn);

let characterDiv=document.querySelector("#character-div");
console.log(characterDiv);

let charPar=document.querySelector("#character-parent")
console.log(charPar);

let incrementer=1;
console.log(incrementer);


//add an event listener to add character button to duplicate html and increment their classes.
newCharacterBtn.addEventListener("click",()=>{
console.log(incrementer)
console.log(characterDiv)

        characterDiv.innerHTML =`
                <div ></div>
                <button >Submit</button><input  type=number></input>
            `
            charPar.append(characterDiv)
            console.log(charPar)

        incrementer=incrementer 1
        console.log(incrementer)// log the increment value.

        let characterInput=document.querySelector(".character-input")
    console.log(characterInput) // log the first character input

    //  let submitBtn=document.querySelector(`#submit-btn${incrementer}`)
    //console.log(submitBtn) //log the all of the submitBtns 

        let iniativeDiv=document.querySelector(`.iniative${incrementer}`)

        let submitBtn=charPar.querySelector(`.submit-btn${incrementer}`)
        console.log(submitBtn)//my failed attempt to log out the submit button.
    });```
 






CodePudding user response:

It looks like you might be incrementing the variable incrementer after you append it to the dom.

specifically this line:

charPar.append(characterDiv)
console.log(charPar)

incrementer = incrementer   1 // NOTE!: this line is the problem!!
console.log(incrementer)// log the increment value.

if you want to access your submit button as a hack, just do this:

let iniativeDiv = document.querySelector(`.iniative${incrementer}`)

let submitBtn = charPar.querySelector(`.submit-btn${incrementer-1}`) // NOTE!: THE -1

console.log(submitBtn)//my failed attempt to log out the submit button.
  • Related