in

Manipulating the DOM with Javascript

DOM means Document Object Model.

A few definitions

The DOM is a representation of a webpage where each HTML element can be represented by a box.

The DOM is a fully object oriented representation so for each HTML box there is an object in the DOM that we can interact with.

Javascript and DOM are different. For something to be seen on the front end we need javascript methods to interact and manipulate the DOM.

A method is a function attached to an object. The DOM is an object.

DOM access and manipulation

The document Object

The object that gives us access to the dom is the document Object. And you can access properties of an object by doing object.property.

Therefore to manipulate the DOM start with:

document.

Selecting methods: querySelector() and getElementById()

.querySelector()

The querySelector() allows us to select elements like css or html tags. It will only select the 1st element that it finds.

.getElementById()

This will select an element that has a precise id

Combining document + method

document.querySelector(‘H1’)

This will select the first H1 tag in the DOM

document.querySelector(‘.fish’)

This will select the first class=’fish’

document.querySelector(‘#red’)

This will select the first id=’red’

document.getElementById(‘red’)

This will also select the first id=’red’

It’s time to manipulate the DOM

Once you select the element of the DOM that you want to change, you are now ready to change it.

Change text in the DOM with .textContent =

document.querySelector(‘H1’).textContent = ‘Hello’

This will change the text in the H1 to Hello

Change HTML with .innerHTML=

document.querySelector(‘H1’).innerHTML = <h3>hello but smaller</h3>

This will change the html of the H1 to a H3 and change the text.

Change CSS with .style.

document.querySelector(‘H1’).style.display = ‘none’

This will hide the H1 title

But where do I put this code?

1 – Open your Google Chrome browser

2 – Right click and inspect

3 – Click on Console

4 – Add your document code

Give it a go head to the following page and paste your code in the console : https://www.startupmag.co.uk/learn-to-code/

document.querySelector(‘H1’).textContent = ‘Hello’

The H1 title Learn To Code becomes Hello!! That’s it you’ve manipulated the DOM!! 😅

What do you think?

Written by John

Leave a Reply

Your email address will not be published. Required fields are marked *

Website animation with jQuery

The Terminal – Code quicker with Command lines