Last Updated : Jan 1, 2023
The getElementsByClassName() method of document interface returns an array-like object of all child elements which have all of the given class names.
When called on the document object, the complete document is searched, including the root node.
Here we defined one div tag with id ‘h’ for access html div element by class name then we appending random text on it by innerHTML.
Here we gets element ‘div’ by class name ‘h’ and stored on variable ‘r’.
As we know getElementsByClassName() is array like object so it had multiple collection behavior so we need to specify with position when we appending text on it that’s way we defined ‘0’ th position and appended text.
We can’t append like getElementById() method each method had some differs.
<!DOCTYPE html> <html> <head> <title>GET ELEMENT BY CLASS</title> </head> <body> <div class="h"></div> <script> const r=document.getElementsByClassName('h'); r.innerHTML="Hi Everyone!"; console.log(r); </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 div tag we defined with id attribute ‘h’. In script we defined getting html ‘div’ element by id ‘h’ and stored on variable ‘r’ with keyword ‘const’.
- As we seen appending text on element with the help of class attribute means we need to specify index or position.
- So we specified at ‘0th’ position we appending some text on div element defined in html webpage by innerHTML.
- We displayed result as well at script console for see that result we have to use shortcut ‘ctrl+shit+j’. Then panel will open with result at right hand side.
- Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.
When we executes program on browser we can see the appended message ‘Hi Everyone!’ on webpage and also in console panel. We have seen how to see result on console earlier.
We can also modify that message and also we can add style on div element using class name same as in getElementById() method.