I am using this code to hide and append a custom input after all ".word" elements, which is extremely slow. I suspect this is because it updates the DOM and reflows the document every time.
Is there any way to speed up this? Problem is, as you can see, that each input box is kind of customized with a particular maxlength, lineheight, etc. so it seems to me it is not possible to kind of do the processing before and then append everything to the DOM at the end. Maybe cloning could work, but I don't know how to implement it.
var $elems = $(".word");
$elems.each(function(index, value) {
var $elem = $(this);
var length = $elem.text().length;
var width = $elem.width();
var line_height = $elem.css("font-size");
$elem
.hide()
.after(
'<div class="input-group dict-input-group"><input type="text" class="dict" ' +
'style="width:' +
width +
"px; line-height:" +
line_height +
';" ' +
'maxlength="' +
length +
'" data-text="' +
$elem.text() +
'">' +
'<span class="input-group-append dict-answer d-none"></span></input></div>'
);
});
I solved it with by cloning the container, doing the processing in the cloned element and then replacing the original element:
var $container = $("#text").clone();
var $elems = $container.find(".word");
var $original_elems = $(".word");
$elems.each(function(index, value) {
var $elem = $(this);
var length = $elem.text().length;
var width = $original_elems.eq(index).width();
var line_height = $original_elems.eq(index).css("font-size");
$elem
.hide()
.after(
'<div class="input-group dict-input-group"><input type="text" class="dict" ' +
'style="width:' +
width +
"px; line-height:" +
line_height +
';" ' +
'maxlength="' +
length +
'" data-text="' +
$elem.text() +
'">' +
'<span class="input-group-append dict-answer d-none"></span></div>'
);
});
$("#text").replaceWith($container);