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

Conteúdo do Curso

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

bookChanging 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

css

index

js

index

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

css

index

js

index

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

css

index

js

index

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

css

index

js

index

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

css

index

js

index

copy
1. How do you change the content of <div id = 'myDiv'> Some Text</div> to : 'I have changed'.
2. How do you change the text content of the 2nd and 3rd elements below using JavaScript?
How do you change the content of <div id = 'myDiv'> Some Text</div> to : 'I have changed'.

How do you change the content of

Some Text
to : 'I have changed'.

Selecione algumas respostas corretas

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

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

Selecione algumas respostas corretas

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 2
some-alt