Text and Attributes Manipulation
Now that we know how to access elements, it’s time to bring them to life! Let’s start by manipulating the text within the elements and their attributes.
Text handling with innerHTML and textContent
To change text within an element, we have two options: innerHTML and textContent.
// Using innerHTML var my Paragraph = document.getElementById('myParagraph'); myParagraph.innerHTML = 'New text here!'; // Using textContent var myTitel = document.getElementById('myTitel'); myTitle.textContent = 'A New Title';
The difference? innerHTML interprets any HTML within the text, while textContent treats everything as simple text.
Attribute manipulation with getAttribute and setAttribute
Now, to move attributes, we use getAttribute and setAttribute.
var myLink = document.getElementById('meuLink'); // Taking the value of an attribute var hrefValor = myLink.getAttribute('href'); // Changing the value of an attribute MyLink.setAttribute('href', 'https://www.novolink.com');
Here, we are picking up and changing the value of the href attribute of a link.
Practical Exercise: Create a Night Mode Button
Let’s apply what we learned! Create a button that, when clicked, changes the text of all paragraphs to white and the background to black, simulating a night mode.
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Practical Exercise: Night Mode</title> <link rel="tylesheet" href="styles.css"> </head> <body> <button id="botaoModeNight">Night Mode</button> <p>Example text 1.</p> <p>Example text 2.</p> <p>Example Text 3.</p> <script src="script.js"></script> </body> </html>
CSS
body { font-family: Arial, sans-serif; } button { padding: 10px; background-color: #3498db; color: #fff; border: none; cursor: pointer; } p { padding: 10px; margin: 10px 0; background-color: #ecf0f1; color: #333; }
JavaScript
document.getElementById('bootNoteMode').addEventListener('click', function() { var paragraphs = document.querySelectorAll('p'); paragrafos.forEach(function(paragraph) { paragrafo.style.color = 'white'; paragrafo.style.backgroundColor = 'black'; }); });
Here, we add an event listener to the button that, when clicked, selects all paragraphs and changes their colors.
Try it! Modify and better that code, that’s how you learn. In the next topic, we will learn how to add and remove elements, further expanding our power of manipulation.