Changing Content - 6.3 | Chapter 6: Advanced DOM Manipulation (JavaScript) | Full Stack Web Development Basics
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβ€”perfect for learners of all ages.

games

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Understanding .textContent

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today, we will explore how to change content using JavaScript. What do you think .textContent is used for, Student_1?

Student 1
Student 1

.textContent is used to change the text inside an HTML element, right?

Teacher
Teacher

Exactly! It helps in setting or retrieving the text without interpreting any HTML. Can anyone explain how it differs from .innerHTML?

Student 2
Student 2

.innerHTML can include HTML markup, while .textContent just deals with plain text.

Teacher
Teacher

Correct! Remember, you can use .textContent if you want to ensure that no HTML gets executed. Let's see an example where we change a paragraph's content.

Student 3
Student 3

Can we update it to say 'Hello World'?

Teacher
Teacher

Sure, here’s how that would look in code: `document.getElementById("greet").textContent = "Hello World!";`.

Teacher
Teacher

What did we learn today about .textContent?

All Students
All Students

It changes the text content of an element!

Using .innerHTML

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Let’s move on to .innerHTML. What do you think it does, Student_4?

Student 4
Student 4

.innerHTML lets you add HTML elements to the content?

Teacher
Teacher

Right! It's useful when you need to insert more complex structures. Would you like to see how we can use it to add a list?

Student 1
Student 1

Yes! Can we add a new <li> item to a list?

Teacher
Teacher

Absolutely! For example, we can change a list with: `document.getElementById("taskList").innerHTML += '<li>New Task</li>';`. This will append 'New Task' to the existing list!

Student 2
Student 2

So, we need to use .innerHTML if we want formatted text?

Teacher
Teacher

Precisely! Remember, however, that using .innerHTML can expose your app to XSS attacks if user input is not sanitized. Always be cautious!

Student 3
Student 3

The careful handling of .innerHTML is crucial for security!

Practical Example: Changing Content

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now let's apply what we learned in a hands-on example. How about creating a function that changes greeting text upon a button click?

Student 4
Student 4

That sounds fun! What do we need?

Teacher
Teacher

We need a button and a paragraph to change the text. Here’s an idea: a button saying 'Greet' and changing a message below it.

Student 1
Student 1

Let's set the initial text in the paragraph as 'Hello'.

Teacher
Teacher

Excellent! When the button is clicked, we can set the paragraph's text content to something new. For example: `document.getElementById('greet').textContent = 'Welcome on board!'`.

Student 2
Student 2

This brings interactivity to our web page!

Teacher
Teacher

Yes, and adding interactivity is key in modern web applications!

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

This section teaches how to dynamically change the content of HTML elements using JavaScript.

Standard

In this section, you'll learn to manipulate the content of HTML elements using properties like .textContent, .innerHTML, and .innerText. You'll see practical examples demonstrating these changes, aiding in understanding how to interactively update web pages.

Detailed

Changing Content

This section focuses on how to modify the content of HTML elements dynamically through JavaScript. Different properties, including .textContent, .innerHTML, and .innerText, are utilized to update element content depending on the necessary output. Understanding these differences is crucial for achieving the desired manipulations on web pages effectively.

Key Points:

  • .textContent: This property sets or retrieves the text content of a node and its descendants, but it does not parse any HTML.
  • .innerHTML: Unlike .textContent, this property allows the inclusion of HTML markup, which can be useful when you need to insert elements or structure into your content.
  • .innerText: Retrieves or sets the visible text of the element, taking into account hidden elements which do not get considered with .textContent.

Example:

Code Editor - javascript
`, -1); codePreview5e954e6917ed4ceaba7bcd534500bf07.setTheme('ace/theme/textmate'); // Attach try it yourself button listener document.getElementById(`try-it-5e954e6917ed4ceaba7bcd534500bf07`).addEventListener('click', () => { switchToEditor5e954e6917ed4ceaba7bcd534500bf07(); }); function switchToEditor5e954e6917ed4ceaba7bcd534500bf07() { // Initialize the editor editor5e954e6917ed4ceaba7bcd534500bf07 = ace.edit("5e954e6917ed4ceaba7bcd534500bf07") setLanguage5e954e6917ed4ceaba7bcd534500bf07(language5e954e6917ed4ceaba7bcd534500bf07); editor5e954e6917ed4ceaba7bcd534500bf07.setValue(`

Hi there!

`, -1); initEditorSettings5e954e6917ed4ceaba7bcd534500bf07(); attachEventListeners5e954e6917ed4ceaba7bcd534500bf07(); document.getElementById(`editor-container-5e954e6917ed4ceaba7bcd534500bf07`).classList.remove('hidden'); document.getElementById(`preview-container-5e954e6917ed4ceaba7bcd534500bf07`).classList.add('hidden'); } function switchToPreview5e954e6917ed4ceaba7bcd534500bf07() { // Clean up the editor instance editor5e954e6917ed4ceaba7bcd534500bf07.destroy(); editor5e954e6917ed4ceaba7bcd534500bf07 = null; document.getElementById(`editor-container-5e954e6917ed4ceaba7bcd534500bf07`).classList.add('hidden'); document.getElementById(`preview-container-5e954e6917ed4ceaba7bcd534500bf07`).classList.remove('hidden'); // Reattach the try it yourself button listener document.getElementById(`try-it-5e954e6917ed4ceaba7bcd534500bf07`).addEventListener('click', () => { switchToEditor5e954e6917ed4ceaba7bcd534500bf07(); }); } function initEditorSettings5e954e6917ed4ceaba7bcd534500bf07() { editor5e954e6917ed4ceaba7bcd534500bf07.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }); editor5e954e6917ed4ceaba7bcd534500bf07.setTheme('ace/theme/xcode'); editor5e954e6917ed4ceaba7bcd534500bf07.session.setMode(`ace/mode/${language5e954e6917ed4ceaba7bcd534500bf07}`); } function setLanguage5e954e6917ed4ceaba7bcd534500bf07(lang) { language5e954e6917ed4ceaba7bcd534500bf07 = lang; editor5e954e6917ed4ceaba7bcd534500bf07.session.setMode(`ace/mode/${lang}`); } // Add method to update code programmatically function setCode5e954e6917ed4ceaba7bcd534500bf07(code) { editor5e954e6917ed4ceaba7bcd534500bf07.setValue(code, -1); } function toggleTheme5e954e6917ed4ceaba7bcd534500bf07() { const isDarkMode = editor5e954e6917ed4ceaba7bcd534500bf07.getTheme() === 'ace/theme/monokai'; const sunIcon = document.getElementById(`theme-icon-5e954e6917ed4ceaba7bcd534500bf07`); const moonIcon = document.getElementById(`moon-icon-5e954e6917ed4ceaba7bcd534500bf07`); if (isDarkMode) { editor5e954e6917ed4ceaba7bcd534500bf07.setTheme('ace/theme/xcode'); sunIcon.classList.remove('hidden'); moonIcon.classList.add('hidden'); } else { editor5e954e6917ed4ceaba7bcd534500bf07.setTheme('ace/theme/monokai'); sunIcon.classList.add('hidden'); moonIcon.classList.remove('hidden'); } } function removeTrailingSpaces(base64String) { // Trim the string to remove any trailing newline characters return btoa(atob(base64String).trim()); } async function runCode5e954e6917ed4ceaba7bcd534500bf07() { const code = btoa(editor5e954e6917ed4ceaba7bcd534500bf07.getValue()); const stdIn = btoa(document.getElementById("input-5e954e6917ed4ceaba7bcd534500bf07").value); const loader = document.getElementById(`run-loader-5e954e6917ed4ceaba7bcd534500bf07`); const output = document.getElementById(`output-5e954e6917ed4ceaba7bcd534500bf07`); const outputContainer = document.getElementById(`run-output-5e954e6917ed4ceaba7bcd534500bf07`); const batchOutputContainer = document.getElementById(`batch-run-output-5e954e6917ed4ceaba7bcd534500bf07`); loader.classList.remove('hidden'); outputContainer.classList.remove('hidden'); output.innerHTML = ''; try { const response = await fetch('/code/api/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: language5e954e6917ed4ceaba7bcd534500bf07, language_id: getLanguageId5e954e6917ed4ceaba7bcd534500bf07(language5e954e6917ed4ceaba7bcd534500bf07), source_code: code, std_in: stdIn, submission_type: 'run', test_cases: [] || [], }), }); const codeResult = await response.json(); if (Array.isArray(codeResult)) { outputContainer.classList.add("hidden"); batchOutputContainer.classList.remove("hidden"); batchOutputContainer.innerHTML = `
${codeResult?.map((result, index) => { const testCaseStatus = result.is_public ? removeTrailingSpaces(result.stdout) === result.expected_output : result.status; return `
${testCaseStatus ? `` : ``} Test Case ${index + 1} ${!result.is_public ? `` : ``}
`; }) .join("")}
${codeResult && codeResult[0] ? atob(codeResult[0].stdin) : "No input available"}
${codeResult && codeResult[0] ? atob(codeResult[0].expected_output) : "No expected output available"}
${codeResult?.[0]?.stderr || codeResult[0].compile_output ? atob(codeResult[0].stderr || codeResult[0].compile_output) : codeResult?.[0] ? (codeResult[0].stdout == null ? "" : atob(codeResult[0].stdout)) : "No output available"}
`; codeResult?.forEach((result, index) => { const codeResult = result; document.getElementById(`testCase-${index}`).addEventListener("click", () => { Array.from(document.querySelectorAll('[id*="testCase"]'))?.map(testCase => { if (testCase.id === `testCase-${index}`) { testCase.classList.add("lg:scale-105", "border", "border-gray-200"); testCase.classList.remove("scale-100", "border-none"); } else { testCase.classList.add("scale-100", "border-none"); testCase.classList.remove("lg:scale-105", "border", "border-gray-200"); } }) if (!result.is_public) { document.getElementById("test-result").innerHTML = `

Hidden Test Case

` return; } document.getElementById("test-result").innerHTML = `
${codeResult ? atob(codeResult.stdin) : "No input available"}
${codeResult ? atob(codeResult.expected_output) : "No expected output available"}
${codeResult ? (codeResult.stderr || codeResult.compile_output ? atob(codeResult.stderr || codeResult.compile_output) : codeResult.stdout == null ? "" : atob(codeResult.stdout)) : "No output available"}
`; }); }); } else { batchOutputContainer.classList.add("hidden") outputContainer.classList.remove('hidden') output.textContent = codeResult.stderr ? atob(codeResult.stderr) : atob(codeResult.stdout || ''); } } catch (error) { console.error(error); } finally { loader.classList.add('hidden'); } } function getLanguageId5e954e6917ed4ceaba7bcd534500bf07(language) { const languages = { javascript: 63, python: 71, java: 62, c_cpp: 49, }; return languages[language]; } function attachEventListeners5e954e6917ed4ceaba7bcd534500bf07() { document .getElementById(`theme-toggle-5e954e6917ed4ceaba7bcd534500bf07`) .addEventListener('click', toggleTheme5e954e6917ed4ceaba7bcd534500bf07); document .getElementById(`run-code-5e954e6917ed4ceaba7bcd534500bf07`) .addEventListener('click', runCode5e954e6917ed4ceaba7bcd534500bf07); document .getElementById(`view-preview-5e954e6917ed4ceaba7bcd534500bf07`) .addEventListener('click', switchToPreview5e954e6917ed4ceaba7bcd534500bf07); }

This code modifies the greeting text from "Hi there!" to "Welcome!", illustrating practical usage of .textContent. Thus, manipulating content is a foundational skill in integrating behavior dynamically into web applications.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Changing Content Methods

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Use .textContent, .innerHTML, or .innerText to change content.

Detailed Explanation

In this chunk, we discuss the three main properties in JavaScript that you can use to alter the content of HTML elements on a web page. All three properties serve to modify the text or HTML within an element, but they have different applications:

  1. .textContent: This property allows you to retrieve or modify the plain text of an element. It does not interpret any HTML tags and simply returns or sets the text as it is.
  2. .innerHTML: This property lets you get or set the HTML inside an element. If you use it to set HTML, any HTML tags included will be rendered as part of the document. This is useful for adding elements or formatting.
  3. .innerText: Similar to textContent, but unlike textContent, it takes into account CSS styles and renders only the text, excluding hidden elements. This means if something is styled to be invisible, it won’t be counted in innerText.

Each method can be useful depending on whether you're only updating text or also want to incorporate formatting.

Examples & Analogies

Think of .textContent like writing a message on a piece of paper; only the words matter. Using .innerHTML is like painting a picture; you can add colors and shapes (HTML tags) to create a detailed image. .innerText is like reading a book where only the visible words on the page count, ignoring any scribbles in the margins.

Example of Changing Content

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Example:

Hi there!

Detailed Explanation

In the example given, we see a practical application of changing content using JavaScript. The HTML contains a paragraph element with the ID 'greet' that originally displays 'Hi there!'. In the script, we use document.getElementById("greet") to access this paragraph element and change its text content to 'Welcome!' using the .textContent property. This code changes what is displayed on the web page dynamically without needing to refresh or replace the entire content.

This demonstrates how JavaScript can interact with HTML to enhance the user experience by changing displayed information based on actions that occur on the page.

Examples & Analogies

Imagine you have a digital sign at a store that says 'Open'. If you wanted to change it to 'Closed' without taking down the whole sign, you could just change the message displayed. Similarly, the JavaScript code we discussed allows you to change what is shown on a webpage effortlessly, just like updating that sign.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • .textContent: Changes plain text of an element.

  • .innerHTML: Allows HTML content to be inserted.

  • .innerText: Reflects only visible text of an element.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • To change the content of a paragraph with id 'greet' to 'Welcome!' using: document.getElementById('greet').textContent = 'Welcome!';

  • To add a new item to a list with id 'taskList': document.getElementById('taskList').innerHTML += '

  • New Task
  • ';

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎡 Rhymes Time

  • Text put in .textContent, won't parse or bend, just plain text till the end.

πŸ“– Fascinating Stories

  • Imagine a book; .textContent only shows the words, while .innerHTML creates illustrations in those pages.

🧠 Other Memory Gems

  • For changing content, remember: TEXT is for plain, INNER is for HTML, and VISUAL is what you see.

🎯 Super Acronyms

TIV - Text for .textContent, Inner for .innerHTML, Visible for .innerText.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: .textContent

    Definition:

    A property used to get or set the text content of a specified node and its descendants.

  • Term: .innerHTML

    Definition:

    A property that can be used to set HTML content inside an element and allows HTML markup.

  • Term: .innerText

    Definition:

    A property that retrieves or sets the text of a node, but only the visible content.