Skip to main content
Practice

Methods to Select 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 id of intro
<!-- HTML p element with id -->
<p id="intro">Hello</p>
JavaScript: Selecting element with getElementById
// Selecting the element and changing its content using JavaScript
const introElement = document.getElementById('intro');
introElement.textContent = 'Welcome';

getElementsByTagName

document.getElementsByTagName() is a method used to select all elements with a specific tag name in HTML.

Code Example:

HTML: multiple p elements
<!-- Multiple <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
// Selecting all elements with <p> tag using JavaScript
const paragraphs = document.getElementsByTagName('p');

for (let para of paragraphs) {
para.style.color = 'blue';
}

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.