Change innerhtml of all h2 elements in div

This is probably a stupid mistake, but I can not get it to work. I am trying to change the innerhtml of all H2 elements using div, id = variable id.

var numberOfQuestions = $('.question').length; var id = "question"+(numberOfQuestions); clone.id=id; document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions); 

I think I'm doing something wrong: document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions); Nrtire script:

  <script type="text/javascript"> function copyAppendRow() { var question = document.getElementById("question"); var clone=question.cloneNode(true); var numberOfQuestions = $('.question').length; var id = "question"+(numberOfQuestions); clone.id=id; var questiondiv = document.getElementById(id); var h2s = questiondiv.getElementsByTagName("h2"); for(var h = 0; h < h2s.length; h++ ) { h2s[h].innerHTML = "Question"+(numberOfQuestions); } if($('#questionsuccess').css('display') == 'none'){ $('#questionsuccess').fadeIn('fast'); $('#questionsuccess').fadeOut(4000); } } </script> 
+4
source share
2 answers

You mean something like:

 var divEle = document.getElementById("yourDivId"); var h2s = divEle.getElementsByTagName("h2"); for(var h = 0; h < h2s.length; h++ ) { h2s[h].innerHTML = "Question"+(numberOfQuestions); } 

OR jQuery Method:

 $("#"+yourDivId + " > h2").html("Question"+(numberOfQuestions)); 
+7
source

I can see from your first line that you are already using jQuery, so make life easy for yourself and use it to complete this task.

 $('#' + id + ' h2').html( 'Question ' + numberOfQuestions ); 

JQuery selectors work just like a CSS selector. Thus, this line of code finds the element with your id variable as its identifier and gets all the h2 tags inside this element. .html is a jQuery method that sets the internal HTML of an element.

+2
source

Source: https://habr.com/ru/post/1438222/


All Articles