How to get the DOM object? In JavaScript, you can get a DOM object using the following methods: getElementById(): Get a DOM element based on its ID attribute. getElementsByClassName(): Gets a collection of DOM elements based on the class attribute. getElementsByTagName(): Gets a collection of DOM elements based on tag names. querySelector(): Get a single DOM element based on a CSS selector. querySelectorAll(): Gets a collection of DOM elements based on CSS selectors.
How to get the DOM object in JavaScript
In JavaScript, there are several ways to get the Document Object Model (DOM) Object:
1. getElementById()
This method is used to get the DOM element based on its ID attribute.
<code class="javascript">const element = document.getElementById('my-element');</code>
2. getElementsByClassName()
This method is used to get a set of DOM elements based on their class attribute.
<code class="javascript">const elements = document.getElementsByClassName('my-class');</code>
3. getElementsByTagName()
This method is used to get a set of DOM elements based on their tag names.
<code class="javascript">const elements = document.getElementsByTagName('p');</code>
4. querySelector()
This method is used to get a single DOM element based on a CSS selector.
<code class="javascript">const element = document.querySelector('p#my-paragraph');</code>
5. querySelectorAll()
This method is used to get a set of DOM elements based on CSS selectors.
<code class="javascript">const elements = document.querySelectorAll('.my-class');</code>
Example
The following example uses the getElementById()
method to get a paragraph element with the ID "my-paragraph":
<code class="javascript">const paragraph = document.getElementById('my-paragraph'); paragraph.innerHTML = 'Hello, JavaScript!';</code>
The above is the detailed content of How to get dom object in javascript. For more information, please follow other related articles on the PHP Chinese website!