<html>
tag is the root, branching out to <head>
and <body>
, which further branch into other elements like <title>
, <div>
, and <p>
. JavaScript lets you access, modify, add, remove, and rearrange these elements.
<code class="language-javascript">const element = document.getElementById('myId');</code>
<code class="language-javascript">const elements = document.getElementsByClassName('myClass');</code>
<code class="language-javascript">const paragraphs = document.getElementsByTagName('p');</code>
<code class="language-javascript">const firstElement = document.querySelector('.myClass'); // First element matching the selector const allElements = document.querySelectorAll('.myClass'); // All matching elements</code>
<code class="language-javascript">document.getElementById('example').textContent = 'New Text';</code>
<code class="language-javascript">document.getElementById('example').innerHTML = '<b>Bold Text</b>';</code>
<code class="language-javascript">const image = document.querySelector('img'); image.setAttribute('src', 'newImage.jpg'); image.setAttribute('alt', 'New Description');</code>
.style
or CSS classes:
<code class="language-javascript">const box = document.getElementById('box'); box.style.backgroundColor = 'blue'; box.style.color = 'white'; box.classList.add('active'); box.classList.remove('inactive'); box.classList.toggle('highlight');</code>
<code class="language-javascript">const newDiv = document.createElement('div'); newDiv.textContent = 'I am a new div!'; document.body.appendChild(newDiv);</code>
<code class="language-javascript">const element = document.getElementById('removeMe'); element.remove();</code>
click
, mouseover
, keydown
, etc.
.parentNode
, .parentElement
, .children
, .childNodes
, .nextElementSibling
, and .previousElementSibling
to access related elements.
documentFragment
to add multiple elements efficiently.innerHTML
: Use createElement
for better performance and security.The above is the detailed content of Understanding DOM Manipulation in JavaScript: A Beginner's Guide. For more information, please follow other related articles on the PHP Chinese website!