Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Changing the Contents of HTML Elements | DOM and HTML Manipulation
HTML & JavaScript Interactivity for Beginners
course content

Contenuti del Corso

HTML & JavaScript Interactivity for Beginners

HTML & JavaScript Interactivity for Beginners

1. DOM and HTML Manipulation
2. DOM Event Handling and Forms
3. JavaScript HTML5 APIs
4. Beginner Projects with HTML + JavaScript

book
Changing the Contents of HTML Elements

In this chapter, you'll find out how to change the contents of HTML elements using the innerHTML property. Then you'll find out how to get and change the attribute values of HTML elements. But first, let's start with how to find HTML elements.

Finding and Changing HTML Elements

By now, you have three methods from the last chapter, and they're :

  • Get elements by id;
  • Get elements by tag name;
  • Get elements by class name.

In this chapter, you'll learn two more methods:

  • Get elements by CSS selectors;
  • Get elements by HTML object collections.

Let's turn into coding examples to see how they operate:

HTML Elements by id

In this coding example, you'll find the <h2> tag by id and change its contents.

html

index.html

copy

HTML Elements by Tag Name

In this coding example, you'll find all the <h2> tags by tag name and display the first element's content on a fresh <p> tag with the id 'demo'.

html

index.html

copy

HTML Elements by Class Name

There are HTML elements with class attributes. So the below program grabs them and displays one of their content in a fresh <p> tag with the id 'demo'.

html

index.html

copy

HTML Elements by CSS Selectors

In this example, first, we'll find the paragraphs under <div> element with id 'main-content' using document.querySelectorAll method. Then we'll change the text of the first paragraph.

html

index.html

copy

HTML object collections

In a web page or an application, there can be a collection of HTML elements, such as forms which houses a group of form controls. In the example below, we grab the value attribute of all the form elements.

html

index.html

copy

1. How do you change the content of
Some Text
to : 'I have changed'.

2. How do you change the text content of the 2nd and 3rd elements below using JavaScript?

question mark

How do you change the content of

Some Text
to : 'I have changed'.

Select the correct answer

question mark

How do you change the text content of the 2nd and 3rd elements below using JavaScript?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 2
Siamo spiacenti che qualcosa sia andato storto. Cosa è successo?
some-alt