Selecting HTML Elements - 1
getElementById
document.getElementById()
is a method used to select an element with a specific id
attribute in HTML.
Code Example:
HTML: p element with intro id
<!-- HTML p element with an id -->
<p id="intro">Hello</p>
JavaScript: Selecting element with getElementById
// Using JavaScript to select the element and change its content
const introElement = document.getElementById('intro');
introElement.textContent = 'Nice to meet you';
getElementsByTagName
document.getElementsByTagName()
is a method used to select all elements with a specific tag in HTML.
Code Example:
HTML: Multiple p elements
<!-- Several <p> elements in HTML -->
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
JavaScript: Selecting elements with getElementsByTagName
// Using JavaScript to select all elements with <p> tags
const paragraphs = document.getElementsByTagName('p');
for (let para of paragraphs) {
para.style.color = '';
}
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.