The document object provides various methods to access and modify HTML documents, including: Get the element with the specified ID (via getElementById) Get the element collection based on the tag name (via getElementsByTagName) Get the element collection based on the class name (via getElementsByClassName ) Find elements using CSS selectors (via querySelector and querySelectorAll) Create new elements (via createElement) Remove elements from the document (via removeChild) Append elements to the document (via
Methods of the document object in JavaScript
The document object plays a vital role in JavaScript, providing a wide range of methods to access and modify HTML documents. The following are some common methods of document objects:
1. getElementById(id)
Get the HTML element with the specified ID.
Example:
<code class="javascript">const element = document.getElementById('my-element');</code>
2. getElementsByTagName(name)
Get the collection of HTML elements with the specified tag name
Example. :
<code class="javascript">const elements = document.getElementsByTagName('p');</code>
3. getElementsByClassName(name)
Get the collection of HTML elements with the specified class name
Example:
<code class="javascript">const elements = document.getElementsByClassName('my-class');</code>
4. querySelector(selector)
Use the CSS selector to find the first HTML element that meets the conditions. #Example:
<code class="javascript">const element = document.querySelector('div.my-div');</code>
Use CSS selector to find all HTML elements that meet the conditions
Example:
<code class="javascript">const elements = document.querySelectorAll('p.my-paragraph');</code>
Create a new HTML element
Example:
<code class="javascript">const element = document.createElement('p');</code>
Remove an HTML element from the document
Example:
<code class="javascript">document.body.removeChild(element);</code>
Append an HTML element to the document.
Example:
<code class="javascript">document.body.appendChild(element);</code>
Write text in the document.
Example:
<code class="javascript">document.write('Hello, world!');</code>
Write text in the document and wrap it.
Example:
<code class="javascript">document.writeln('Hello, world!');</code>
The above is the detailed content of Methods of document objects in javascript. For more information, please follow other related articles on the PHP Chinese website!