Open In App

What is Document Object in Java DOM?

Last Updated : 08 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Document Object Model is a commendation of the World Wide Web Consortium. It explains an interface that enables programs to access and modify the style, structure, and contents of XML documents. XML parsers that support DOM implement this interface. It can be clearly perceived from the image provided below as follows.

When should one use a DOM parser? 

  1. Use it when you know a lot about the structure of a document.
  2. Use it if you need to use the information in an XML document more than once.
  3. You need to move parts of an XML document around.

What do we get by using DOM?

  • When an XML document is parsed with DOM parser, it gives back a tree structure that contains all the elements of the document.
  • A variety of functions are provided by DOM you can use it to inspect the contents and structure of the document.

Let us discuss the advantages of DOM as listed below:

  • Used for manipulating document structures.
  • Data persists in memory.
  • You can go forwards and backward in the tree (random access)
  • You can make changes directly to the tree in memory.

DOM Interfaces

  • Node: The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types be used similarly and often interchangeably.
  • Element: It represents a program element such as a package, class, or method.
  • Attr: it is used for representing an attribute of an element.
  • Text: It is the actual content of an Element or Attr.
  • Document: Document represents the entire XML document.

Common DOM methods :

Methods Action performed
getElementId() It is used to access any element virtually. It accesses the first element with the specified ID.
getElementsByTagName()  In the previous method, we may have some errors. But this method can eradicate those issues. getElementByTagName allows you to search all the elements with a specified tag name on your page.
getElementsByClassName It will also return a live HTMLCollection of all those elements that have the same class added to them. If no element is found then it returns an empty HTMLCollection
querySelectorAll It will return the first element that matches the specified group of selectors. If no match is found ‘null’ is returned.
querySelector It returns all the elements that match the specified CSS selectors .

Any element on a page including text & whitespaces of a DOM structure is known as “NODE.” Nodes can be between XHTML Tags.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads