doctor
doctor

Reputation: 11

how do I make a function in javascript that returns an HTML element

I was writing a javascript code trying to get an HTML element

function getOutput(){
    return document.getElementById("output-value").innerText;
}

but when I make a alert( getOutput()) the browser just sends me the lines of code above how do I fix this ?

I tried to fix it by this:

function getOutput(){
    return document.getElementById("output-value").innerHTML;
}

and also this

function getOutput(){
    return document.getElementById("output-value");
}

but none seemed to work What should I do ?

Upvotes: 0

Views: 79

Answers (1)

Towkir
Towkir

Reputation: 4004

but when I make a alert( getOutput()) the browser just sends me the lines of code above how do I fix this ?

The only way that would happen is if you put your statement inside of a quotation mark. See: getOutputString() function in the snippet

If you are looking to the child elements, .innerHTML is your thing. And if you are trying to get the element with the id itself, then .outerHTML is what you are looking for.

Check the snippet:

function getOutput(){
    return document.getElementById("output-value").innerHTML;
}

function getOutputString(){
    return 'document.getElementById("output-value").innerHTML;'
}

function getOutputEl(){
    return document.getElementById("output-value").outerHTML;
}


alert(getOutput());
alert(getOutputString());
alert(getOutputEl());
<div id='output-value'>
<p>Test texts</p>
</div>

Upvotes: 2

Related Questions