Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 class="favorite__page JS-favoritePage">
            <p id="JS-amountOfFavorites">Quantity of saved pages : ${amount}</p>
            <input type="number" class="favoritesQuantity" 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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?

>Solution :

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 class="favorite__page JS-favoritePage">
            <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 [class="favoritesQuantity"]');

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading