I have an html file that consists of a table with fields inside. Some fields are marked by xxx, which should be converted to textareas. That has been successfully done as:
function raplace() {
var replaced = $("body").html().replace(/xxx/g,'<textarea class="textarea" id=0 style="width: 100%; height: 100%; min-height:3em; box-sizing: border-box; resize: none; border:none"></textarea>');
$('body').html(replaced);
}
The task is now to assign a name attribute that should be for the first textarea name="text1"
, for the second area name="text2"
and so on.
To accomplish this I purposely set id=0
for all text areas, as you can see form the code above. I have tried to accomplish the goal by using this code:
var i=1;
while (document.getElementById('0')) {
//$('#0')[0].name = 'text'+i;
//$('#0')[0].id = i;
document.getElementById("0").name = "text" + i;
document.getElementById("0").id = i;
//document.getElementById("0").setAttribute("name","text"+i);
//document.getElementById("0").setAttribute("id",i);
i++;
As you may know, all three codes above are working and do the same thing. However, here comes the big problem.
When i put the code into the browser console, it does as expected, changing name and id attributes perfectly. However, if the code is put into my file, it only generates the textareas, setting all id=0. The second part of the script (to change the attribute values) is not executed. I have been looking all over the web for many days now, and have resorted to ask here at stack overflow. It If anyone can help me out, it would be amazing. Thanks!!!
NOTE: the first part needs to be executed first, or otherwise you would not have an id to target.
EDIT: After cleaning up the code a bit, here is what I have. If anyone knows why the second part does not execute, please let me know. Thanks!
function raplace() {
var replaced = $("body").html().replace(/xxx/g,'<textarea class="replacement" style="width: 100%; height: 100%; min-height:3em; box-sizing: border-box; resize: none; border:none"></textarea>');
var replacements = document.getElementsByClassName('replacement');
var txtArea;
for (var i = 0; i < replacements.length; i++) {
txtArea = replacements[i];
txtArea.id = "text" + i;
txtArea.name = "text" + i;
}
$('body').html(replaced);
}