Reputation: 886
I have a simple class that has a parent element, and i store it's child element progress, but when I add to the child element nothing happens
class MyClass {
constructor(element) {
this.elem = element;
this.child = this.elem('.child');
this.fill();
}
fill() {
this.elem.innerHTML += '<span class="child2"></span>';
}
update(val) {
this.child.style.width = val + '%';
}
}
When I call the update function nothing happens. If I print the child element I see that it has a style of val%
but I don't see it "update" in the DOM.
It's like it is copying the object and not storing the reference.
BTW:
Also this works ok this.elem.querySelector('.child').style.width = val + '%';
Also tried with children[0]
also won't work.
Thank you in advance!
Upvotes: 0
Views: 26
Reputation: 12637
A simple utility that converts markup to a documentFragment to push around.
var dummy = document.createElement('div');
function fromHTML(markup){
dummy.innerHTML = markup;
for(var frag = document.createDocumentFragment(), fc; fc = dummy.firstChild;)
frag.appendChild(fc);
return frag;
}
so instead of node.innerHTML += someMarkup;
better do node.appendChild( fromHTML(someMarkup) )
in your case
fill() {
this.elem.appendChild( fromHTML('<span class="child2"></span>') );
}
or in this simple case, avoid the markup at all:
fill() {
var child = document.createElement('span');
child.className = "child2"; //avoid enumerated classes/valriables/everything
this.elem.appendChild( child );
}
Upvotes: 1
Reputation: 411
As a commenter said, this is likely to be linked to the use of .innerHTML on a parent node or the node itself. The reason behind this is when you use .innerHTML, JavaScript modifies the DOM and "rebuilds" it inside the node innerHTML. This will release all existing handles to the existing nodes. This means all listeners and references will get lost when you update the innerHTML.
Considering appending instead of editing the innerHTML and this will solve your issue.
Upvotes: 1