I have an html document that contains 4 paragraphs.
I want to take the concatenation of all paragraph's innerHTML and put it in the paragraph with "demo" id. The problem is that it also prints the function's signature...
How can I print only the string that my function returns?
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
<p id="demo"></p>
<script >
var paragraphs = document.getElementsByTagName("p");
function getText() {
var text=null;
for (var i = 0; i < paragraphs.length; i++) {
getText = getText + paragraphs[i].innerHTML;
}
return getText;
}
document.getElementById("demo").innerHTML=getText();
</script>
</body>
</html>
I get this as a result:
Hello World!
The DOM is very useful.
This example demonstrates the getElementsByTagName method
function getText() { var text=null; for (var i = 0; i < paragraphs.length; i++) { getText = getText + paragraphs[i].innerHTML; } return getText; }Hello World!The DOM is very useful.This example demonstrates the getElementsByTagName method
innerHTML. It adds an unnecessary serialization and parsing step to your task (overhead), and if for example some other script would have added event-listener to some of the processed nodes/markup, they would have been gone now; they don't serialize. Better would be to accumulate the childNodes you want in a DocumentFragment (the accumulation prevents multiple render-steps), and to just move/append them to the target Node (demo).