DEV Community

Cover image for Manipulating / Accessing HTML element using JavaScript pt 1
Victoria igbobi
Victoria igbobi

Posted on

Manipulating / Accessing HTML element using JavaScript pt 1

In plain English, DOM provides a way to manipulate or access HTML elements using JavaScript.

Say you want to get the value of an input field or a HTML element into your JavaScript function or code, DOM makes that possible.

It's also possible to get the value of a HTML element and access it using CSS but this article doesn't cover that

METHODS FOR GETTING HTML ELEMENT

So I'd list out the methods before explaining their syntax

  1. getElementByTagName()
  2. getElmentByClassName()
  3. getElementById()
  4. query selector()

getElementByTagName(): Just as the name implies, this methods takes a HTML tag name and returns an array of the HTML element with that tag.
We can then loop through the array to get individual element like we'd loop through every other array.

Basic syntax

//returns an array of all HTML element with the p tag
const elements = document.getElementByTagName('p') 

// Looping through the array of elements 
for (let i=0; i<elements.length; i++){

    //Getting each html element in the array
    Console.log(elements[i])
}
Enter fullscreen mode Exit fullscreen mode

getElementByClassName(): This method takes a class name and returns an array of the HTML elements with that class.
We can loop through the array as we would an array.

Basic syntax

//returns an array of all HTML element with the title class
const elements = document.getElementByClassName('title') 

// Looping through the array of elements 
for (let i=0; i<elements.length; i++){

    //Getting each html element in the array
    Console.log(elements[i])
}
Enter fullscreen mode Exit fullscreen mode

getElementById(): This method takes an id name and returns a single HTML elements with that id.

Basic syntax


const elements = document.getElementById('demo') 
Console.log(elements)

Enter fullscreen mode Exit fullscreen mode

querySelector(): This method takes either an id name or class name or tag name and returns a single HTML elements with that id, class or tag.

Basic syntax


// select the first available h1 element
let firstTitle = document.querySelector('h1') 

// select id with first-title
let firstTitle = document.querySelector('#first-title') 

// select the first available element with class title
let firstTitle = document.querySelector('.title') 
Enter fullscreen mode Exit fullscreen mode

Thanks for the read ❤️

Top comments (1)

Collapse
 
monginadiana profile image
monginadiana

Great article, well articulated.