Last Updated : Jan 1, 2023
The getElementById() method returns an Element object that represents an HTML element with an id that matches a specified string.
This is one of the most common methods in the HTML DOM.
Here we defined label with id attribute ‘lbl’ and it had some text.
In script we defined variable ‘r’ for storing label value and we can display that label value using ‘innerText or textContent’ properties in console.log() method.
The innerText property used to get or set the text inside an HTML element and its descendants and also textContent property had same behavior it returns the content of an element/node and all of its descendents.
<!DOCTYPE html> <html> <head> <title>GET LABEL TEXT</title> </head> <body> <label id="lbl">Welcome message from label</label> <script> var r=document.getElementById('lbl'); console.log(r.innerText); console.log(r.textContent); </script> </body> </html>
- <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in and it’s not have any ending tag.
- The<html> tag is used to indicate the beginning of HTML document.
- As above shown <head> tag is contain information about webpage and external file links are declared here. <title> tag is used for set the webpage title.
- Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If you’re not closed anyone of ending tag properly that is also affect the webpage result.
- <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here.
- Here we defined label tag with id ‘lbl’ and within that we specified some text of ‘Welcome message from label’.
- In script we defined variable ‘r’ for storing label ‘lbl’ value and then collected label value displayed using ‘innerText, textContent’ properties on console panel.
- For seeing result we need to open console panel on browser so we have right click on browser webpage and select ‘inspect’ option then console panel will opened successfully.
- Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.
Then for open console panel we had another option use shortcut ‘ctrl+shift+j’ on browser and at right hand side console panel will open with retrieved label value and it will displayed two time because we used two properties for showing result.