Home > database >  How can you select code nodes that were added through templates?
How can you select code nodes that were added through templates?

Time:04-06

So I am using the template method to dynamically add HTML content in a page, and I want to change the value of an input through an event listener.

Here's a completely random snippet of code as an example (it's nonsensical on purpose):

favoriteElement  =  `<div >
            <p id="JS-amountOfFavorites">Quantity of saved pages : ${amount}</p>
            <input type="number"  name="amountOfFavorites" min="1" max="100" value="${value}">
          </div>`

So let's say that I want to have access to the value of the input, I'll declare a variable and get it through their query selector :

let inputFavoritesQuantity = document.querySelector('input []');

Now I'll add an event listener:

inputFavoritesQuantity.addEventListener("input", function(e){
let valueOfInput = e.target.value;

//Other code
}

Though the problem is that I do not have access to the input because it's added with a template, so it gives an error Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

I could add everything by hand using the properties createElement,setAttribute,appendChild...

But it would make the code VERY long and difficult to maintain! (without even considering the fact on my code project I'd have to add 5 nested elements which have 5 attributes each!)

Is there another efficient method to have access to an element with templates?

CodePudding user response:

The DOMParser compiles strings into a document. You need to access the documentElement in order to add to the existing dom. Here's an example of use

let amount = 100
let value = 50
favoriteElement =  `<div >
            <p id="JS-amountOfFavorites">Quantity of saved pages : ${amount}</p>
            <input type="number" name="amountOfFavorites" min="1" max="100" value="${value}" />
          </div>`

// This converts the string and gets the documentElement.
var node = new DOMParser().parseFromString(favoriteElement, "text/html").documentElement

//Now we are working with an actual element and not a string of text.
let inputFavoritesQuantity = node.querySelector('input []');

node.addEventListener("input", function(e){
    let valueOfInput = e.target.value;
    console.log('value changed', valueOfInput);
})

var outputDiv = document.getElementById('content')
outputDiv.appendChild(node);
<div id="content">

</div>

  • Related