DrMacak DrMacak - 1 year ago 65
HTML Question

How to modify child of new element with JS, when not in page yet

I'm trying to achieve something like templating with JS. The example use-case is, I have page with two objects, rectangle and circle. When I click on rectangle it should show me html button with text DELETE RECTANGLE.

In reality, I will call ajax get on template file (panel.htm) to get what is inside this file. Then I create div element using JS. Then I populate innerHTML with panel.htm(template). In this template is .

What I want is to change this button inner html inside the created and populated div. Im using getByClass because ById is not defined for element.

BUT changes to the button are not propagated/copied to original div.

// Template data
var html = `<div>
<button class="delBtn" type="button">OLD TEXT</button> <br>

// creating new div.
var div = document.createElement('div');

// putting template to new div
div.innerHTML = html;

// accessing the button from the inserted template
div.getElementsByClassName('delBtn').innerHTML = "NEW BUTTON TEXT";

// There I would expect to get div with button inside with NEW TEXT

// In production here will be some insertion to page etc. This is just bare example of code.

I know this is possible to solve using some template framework. But I would like to stay to clean JS if possible. Also this is new for me, so I would like to learn little bit, and I did not manage to find some answer anywhere.

This seems to me like pure basic stuff so I hope this question is not redundant.

Answer Source

The getByClass returns always an HTMLCollection so you might want to get the first like

div.getElementsByClassName('delBtn')[0].innerHTML = "NEW BUTTON TEXT";

This will work!

Also if you want to try it do

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download