0

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 ?

4
  • "but when I make a alert( getOutput()) the browser just sends me the lines of code above" I can't reproduce that. When I use that it displays the inner text just fine. Please post a minimal reproducible example Commented Apr 27, 2019 at 16:37
  • Are you sure you didn't forget the parentheses? There's a difference between alert(getOutput()) and alert(getOutput). Commented Apr 27, 2019 at 16:38
  • check your console for errors Commented Apr 27, 2019 at 16:40
  • hey doc, did my answer help ? if so, you can upvote and accept the answer. thanks Commented Apr 27, 2019 at 18:36

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.