JavaScript JavaScript and the DOM Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

Tomasz Grodzki
Tomasz Grodzki
4,654 Points

Why .textContent doesn't work with const input?

Almost everything's clear. I know how to use input and textContent. But all in all, why input.textContent doesn't work?

const input = document.querySelector ( "input" );
const p = document.querySelector ( "p.description" );
const button = document.querySelector ( "button" );

//button.addEventListener ( 'click', () => p.textContent = input.textContent + ':' ) <--- why it doesn't work the same like this line below?
button.addEventListener ( 'click', () => p.textContent = input.value + ':' )
<!DOCTYPE html>
    <title>JavaScript and the DOM</title>
    <link rel="stylesheet" href="css/style.css">
    <h1 id="myHeading">JavaScript and the DOM</h1>
    <p>Making a web page interactive</p>    
    <p class='description'>Things that are purple:</p>
    <input type="text" class="description">
    <button class='description'>Change list description</button>
    <script src="app.js"></script>

2 Answers

Melvin Ray
Melvin Ray
Pro Student 6,138 Points

I checked and for information on the "textContent" attribute of an <input> tag. According to the first link, textContent returns all elements within a node (some top-level container on a web page, not to be confused with the web server node.js). According to the Chrome browser, <input> must have inherited the attribute from <node>.

However, per the second link provided above, "textContent" is not even listed as an attribute of <input>. I don't think that it should be, because <input> is a self-closing tag. The <input> element cannot contain nodes, because that would require it to have a corresponding </input> tag. The creature simply does not exist.

I assume that the browser that didn't catch the problem of the missing "textContent" attribute of <input> must have a bug. As I write this, Google Chrome is not complaining about the missing attribute. It quietly gives me an empty string.

I hope this helps answer your question.

Tomasz Grodzki
Tomasz Grodzki
4,654 Points

Yes, it is completely helpful. Thank you for your help! I really appreciate such good answer.

When u use query selectors u have to specify the class or the id u used to define the element in the html

Tomasz Grodzki
Tomasz Grodzki
4,654 Points

I would have to if there was more than one input, wouldn't I? Even though, I changed

const input = document.querySelector ( "input" );


const input = document.querySelector ( "input.description" );

And it didn't change anything. What I missed?