Skemelio Skemelio - 2 months ago 7
HTML Question

How to print a function's return string without its body?

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

Answer

Replace your function with :

function getText() {
        var text="";
        for (var i = 0; i < paragraphs.length; i++) {
            text= text+ paragraphs[i].innerHTML;
        }
        return text;
    }

In your case, you were returning getText which is name of your function that's why the method is also getting appended