Alex Alex - 4 months ago 13
HTML Question

Loop through html content using the ids in javascript

I am trying to loop through html content, for each html has a text input which i want to get the text value and pass it to the html span that also has id

replyJail-number
of the same with id of
replybefore-number


HTML PART

<span id="replyJail-1" class="rep"></span>
<input id="replybefore-1" class="brp" type="hidden" value="hello"/>

<span id="replyJail-2" class="rep"></span>
<input id="replybefore-2" class="brp" type="hidden" value="#Bold letter"/>

<span id="replyJail-3" class="rep"></span>
<input id="replybefore-3" class="brp" type="hidden" value="`My code`"/>


Javascript

var x = document.getElementsById(id);
//x[i]
var i;
for (i = 0; i < x.length; i++) {
var n = i++;
var converter1 = Markdown.getSanitizingConverter();
var CODESOFTLAB = new Markdown.Converter(converter1);
var before = document.getElementById("replybefore"+n).value;
var MarckDowPreviewHtml = CODESOFTLAB.makeHtml(before);
document.getElementById("replyJail"+n).innerHTML = MarckDowPreviewHtml;
var a = 10;
}

Answer

You can get all input elements using getElementsByClassName. Now, iterate through each input and get the corresponding span's id by replacing "before" with "Jail". You can now insert the corresponding input's value in the target span as textContent.

var inputs = document.getElementsByClassName("brp");
var converter1 = Markdown.getSanitizingConverter();
var CODESOFTLAB = new Markdown.Converter(converter1);

for( var i = 0; i < inputs.length; i++ )
{
  var input = inputs[i];
  var value = input.value;
  var MarkDownPreviewHtml = CODESOFTLAB.makeHtml(value);
  var targetId = input.id.replace("before", "Jail");
  var targetSpan = document.getElementById( targetId );
  targetSpan.textContent = MarkDownPreviewHtml;
}//for()


<span id="replyJail-1" class="rep"></span>
<input id="replybefore-1" class="brp" type="hidden" value="hello"/>

<span id="replyJail-2" class="rep"></span>
<input id="replybefore-2" class="brp" type="hidden" value="#Bold letter"/>

<span id="replyJail-3" class="rep"></span>
<input id="replybefore-3" class="brp" type="hidden" value="`My code`"/>
Comments