- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript Accessing and Setting Content: Syntax, Usage, and Examples
In JavaScript, accessing and setting content refers to retrieving or changing the visible content inside HTML elements. This is commonly done using properties like .innerHTML
, .textContent
, and .innerText
to create dynamic web pages.
How to Use JavaScript to Access and Set Content
To modify the content of a webpage using JavaScript, you typically start by selecting an element and then changing its content property. The most commonly used property is innerHTML
, which allows you to both read and write HTML inside an element.
const element = document.getElementById("greeting");
element.innerHTML = "Hello, world!";
This line grabs the element with the ID greeting
and updates its content.
You can also read content:
const currentText = element.innerHTML;
console.log(currentText); // Output: Hello, world!
Other content-setting properties include:
.textContent
: sets or retrieves just the text, ignoring any HTML tags..innerText
: similar to.textContent
, but accounts for styling and hidden elements.
When to Use JavaScript to Access or Set Content
Here are some common scenarios when you’d use JavaScript accessing and setting content:
1. Updating User Interface Dynamically
If you want to display a personalized message, notification, or result based on user input or data, changing the content dynamically with JavaScript is essential.
const status = document.getElementById("status");
status.textContent = "Loading...";
2. Responding to Events
Interactive applications often change content in response to user actions, like clicking a button or submitting a form.
document.getElementById("submit").addEventListener("click", () => {
document.getElementById("confirmation").innerText = "Form submitted!";
});
3. Displaying Data from APIs
If your app fetches data from a server (e.g., news headlines or weather), you’ll likely want to inject that data into your HTML dynamically.
fetch("https://api.example.com/joke")
.then(res => res.json())
.then(data => {
document.getElementById("joke").innerHTML = data.text;
});
Examples of Accessing and Setting Content
Example 1: Adding a Message to the Page
const paragraph = document.createElement("p");
paragraph.innerHTML = "Wanna go see a movie?";
document.body.appendChild(paragraph);
This creates a <p>
tag and sets its content, then adds it to the page.
Example 2: Replacing Existing Content
<div id="quote">Old quote here</div>
const quoteBox = document.getElementById("quote");
quoteBox.innerHTML = "“The only limit to our realization of tomorrow is our doubts of today.”";
The quote inside the div
gets replaced with a new one.
Example 3: Handling User Input
<input type="text" id="nameInput">
<button id="greetBtn">Greet</button>
<p id="greeting"></p>
document.getElementById("greetBtn").addEventListener("click", () => {
const name = document.getElementById("nameInput").value;
document.getElementById("greeting").textContent = `Hi, ${name}!`;
});
This displays a greeting using the value the user typed into the input field.
Learn More About JavaScript Content Manipulation
innerHTML
vs textContent
vs innerText
innerHTML
can inject actual HTML (tags, elements, etc.). Be cautious, as this can expose you to cross-site scripting (XSS) if the content comes from users.textContent
only sets or gets the text, not HTML, and is safer when handling user input.innerText
behaves liketextContent
but respects CSS styles such asdisplay: none
.
Example comparison:
<div id="info"><strong>Important</strong> notice</div>
const el = document.getElementById("info");
console.log(el.innerHTML); // <strong>Important</strong> notice
console.log(el.textContent); // Important notice
console.log(el.innerText); // Depends on visibility and styling
Creating and Appending New Content
Instead of modifying existing elements, you can also create new ones from scratch and add them:
const newNote = document.createElement("div");
newNote.textContent = "This is a new note.";
document.body.appendChild(newNote);
You can even include HTML inside with innerHTML
:
newNote.innerHTML = "<strong>Note:</strong> Don’t forget your umbrella.";
Removing or Replacing Content
While accessing and setting content changes the inside of an element, sometimes you want to remove the whole element or swap it.
const message = document.getElementById("temporary");
message.remove(); // Removes the entire element
Or, replace it with a new one:
const parent = document.getElementById("container");
const newElement = document.createElement("div");
newElement.innerHTML = "Updated content!";
const oldElement = document.getElementById("oldContent");
parent.replaceChild(newElement, oldElement);
JavaScript accessing and setting content is one of the first steps toward building interactive webpages. Whether you're adding a welcome message, updating a status indicator, or rendering new data, learning how to control content using innerHTML
, textContent
, and innerText
gives you the tools to make your site feel alive.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.