My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Document Object Model (DOM) in JavaScript

Rahul Sharma's photo
Rahul Sharma
·Aug 30, 2021·

2 min read

DOM

Document Object Model is application programming interface (API) for manipulating HTML and XML documents.

The Document Object Model represent document as a tree of nodes. It provides an API that allows to add, remove, and modify parts of the document effectively.

The Document Object Model is a language-independent and cross-platform ways of manipulating HTML and XML document.

getElementById() method

  • getElementById() returns Document object model element specified by an id that we gives to a tag or null if no matching element found.

  • In getElementById(), if multiple tags are sharing the same id, so in that condition it takes the first element or tag which have id.

id.png

getElementByClass() method

  • getElementsByClassName() is used for selecting the elements on basis of classes
  • getElementsByClassName() available on document object and any HTML element.
  • getElementByClassName() accepts mutiple elements with same class name, in getElementById() it accepts only single elements with same id name.

class.png

querySelector() method

  • querySelector() select the first element by which it matches a CSS selectors or group of CSS selectors.

  • CSS rules applies only on define elements of CSS selectors.

innerHTML

  • innerHTML property is used for change or insert the HTML in selected element.

  • innerHTML return the current html code of that element and if any change has been done before loaded that also return by innerHTML property.

  • We have to avoid innerHTML property for set new content on which we don't have any control to avoid security risk.