Facing problem in document object in Java Script

I am unable to understand the concept of getElementById of document object while writing in console.I am confused with output that we are getting in the webpage.
I am also attaching a screenshot the code written in console where i am facing the confusion.

@20051247 in javaScript, we can access the UI elements through the help of the Document Object. You can understand it in this way, we can access and thus modify the User Interface components via the Document Object Model manipulations.

So either you do the DOM manipulations via the console (web browser) or via the code editor, the end results will remain same.

In JS, we can assign any id or class to a particular HTML element so that later on we can do the DOM manipulations by using that id / class. There are a lot of methods (object’s functions) for the Document Object. For example, say you have defined 50 HTML elements in your file, then getElementById / getElementbyClass method gives you the power to select a particular element from those 50 elements.

So, document.getElementById can be thought of as a selector and then you have to pick which property of the method (getElementById) do you want to choose. There are many properties of the method (like addClassList, removeClassList and many more). So in your case, you have used the inner HTML property of the method getElementById.

In the code you have defined a paragraph tag which has an id of output. So you have selected that para tag with the help of getElementById and then you have written the code to change the HTML content of the paragraph tag to "From Console

As you have just written the document.getElementById(“output”).innerHTML = “From Console” after defining the paragraph tag without specifying any event. That is why at the time of loading the HTML page, the browser first loads the paragraph with the content New Text but when the next line is executed it overwrites the first HTML content and thus you see the From Console in the UI.

I am providing the code in which I have added the onclick event to the paragraph tag. So at the time of loading the p tag will have the default text bu when we click on the text, the function changeText is called which then uses the same concept of innerHTML to change the content’s value.

After we click on the text, the page will look like this:
Change

I hope this clears the doubt :+1:

1 Like

@harshika1406.vats… I got the point… Thank you. It basically means until we type innerHTML,it will print the earlier output from document.getElement.getElementById(“Output”)

Yes you are right.
Now please close the query by clicking on the Solution button in the previous post.

1 Like