InnerHTML returning undefined for <code> tag in HTML

I’m trying to get the text from tag by using the javascript code:

document.getElementById("newTextArea").innerText = document.getElementsByTagName("code").innerHTML;

But when i’m trying to print the value of newTextArea, it reads undefined

I think that getElementsByName gives an array-like nodeList, so if only one of them is expected, you can retrieve node 0 with [0] and then get its innerHTML.

Hi kumaraashish118 welcome to the forum

getElementsByName() returns a node list collection

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName

Of that collection, your code as it is now is not specifying which member of that collection it wants to use.

1 Like

Actually it was TagName, I’ve edited the post

Actually it was TagName , now I’ve edited the post

In that case there is a difference in that it returns a live list. But you would still want to specify which you wanted.

And I’m not so sure it’s a good idea to assign innerHTML to innerText. I think as long as the innerHTML is only text it should be OK but I don’t know how innerText would deal with HTML tags if they were there.

I think this answers that question - https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

For that reason, it is recommended you not use innerHTML when inserting plain text; instead, use node.textContent. This doesn’t interpret the passed content as HTML, but instead inserts it as raw text.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.