What is the process for choosing and making changes to a specific portion of a textContent?

<h1 id="block ">This is my header block</h1>

To dynamically change the color of the "block" word every 2 seconds using JavaScript:

let colors = ["blue", "green", "pink", "purple"];
let curColor = 0;
const changeColor = () => {
    let text = document.querySelector("#block");
    text.innerHTML = text.innerText.replace("block", `<span style="color: ${colors[curColor]}">block</span>`);
    curColor++;
    if (curColor > 3) {
        curColor = 0;
    }
    setTimeout(changeColor, 2000);
}
setTimeout(changeColor, 2000);

This code will change the color of the word "block" within the h1 tag every 2 seconds.

If needed for another element, replace "#block" in the querySelector with the appropriate selector.

Answer №1

One way to highlight a specific word is by enclosing it in another tag, such as <span>.

let colors = ["blue", "green", "pink", "purple"]
let curColor = 0;
let changeColor = () => {
  let element = document.querySelector("#block > span")
  element.style.color = colors[curColor]
  curColor = (curColor + 1) % colors.length;
  setTimeout(changeColor, 2000)
}
setTimeout(changeColor, 2000)
<h1 id="block">This is my header <span>block</span></h1>

Answer №2

const shades = ["red", "yellow", "orange", "brown"]
      let currentShade = 0, intervalId

      changeShade = () => {
         let selectedElement = document.querySelector("#box > span")
         //selectedElement.style.cssText = "color:" + shades[currentShade]
         selectedElement.style.color = shades[currentShade]
         currentShade = ++currentShade % 4
      }

      function initializeShadeChange() {
         if (!intervalId) {
            intervalId = setInterval(changeShade, 2500)
         }
      }

      function stopShadeChange() {
         //execute this to halt shade transition
         clearInterval(intervalId)
         intervalId = null
      }
      
      initializeShadeChange()
<!DOCTYPE html>
<html lang="en">

   <head>
     <meta charset="UTF-8">
     <title>Colorful Page Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
   </head>

   <body>
       <h1 id="box">This is my display <span id="multicolored">panel</span></h1>
  </body>


</html>

Answer №3

I concur with the proposed solutions!

If you prefer to initialize your color and avoid a black block, try this approach:

Furthermore, you can include the colors array and selector as arguments in your function.

        let colors = ["blue", "green", "pink", "purple"];
        let curColor = null;
        let interval;
        let element;
        let query = "#block > span";
    
    function changeColor(cols,query){
        element = document.querySelector(query);
        if(curColor === null){
            curColor = 0;
        }
        element.style.color = cols[curColor];
        curColor = (curColor + 1) % colors.length;
    }
    window.addEventListener("DOMContentLoaded",() => {changeColor(colors,query);})
    interval = setInterval(changeColor,2000,colors,query);
<h1 id="block">This is my header <span>block</span></h1>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...

What methods can be used to construct components using smaller foundational components as a base?

Is there a more elegant approach to constructing larger components from smaller base components that encompass common functionalities, akin to an interface in the OOP realm? I'm experimenting with this concept, but it feels somewhat inelegant. Repor ...

HTML source does not contain nested link elements for linked areas with nested hyperlinks

I want to create a visually and functionally appealing hyperlink within a larger rectangular shape that spans the full width of the page and is also a hyperlink itself. Below, you'll find an ASCII-art representation of what I'm trying to achieve: ...

Discover a non-null string within a deeply nested data structure

Within the 'task' object, the value of the 'door' property can vary each time it is accessed: var task = {}; task["123"] = [{"door":""}, {"door":""}, {"door":""}, {"door":""}]; task["456"] = [{"door":""}, {"door":"close"}, {"door":"" ...

Six Material-UI TextFields sharing a single label

Is there a way to create 6 MUI TextField components for entering 6 numbers separated by dots, all enclosed within one common label 'Code Number' inside a single FormControl? The issue here is that the label currently appears only in the first tex ...

What is the best way to change an array of strings into a single string in JavaScript?

I am working with a JavaScript array that contains strings arranged in a specific format: arrayOfString = ['a', 'b,c', 'd,e', 'f']; My goal is to transform this array into a new format like so: myString = ["a", "b ...

When the submit button on the signup form is pressed, two distinct actions are activated to achieve specific outcomes

I am seeking assistance in implementing code that will trigger the following action: Upon clicking the 'Submit' button on a signup form after the subscriber enters their email address and name, the signup page should reload within the same tab wi ...

A guide on extracting information from a personal Flask JSON route endpoint with Axios

I am looking to store JSON data in a variable using Axios in Javascript. The JSON endpoint is generated by my own server's route http://123.4.5.6:7890/json. I have been successful with this function: async function getClasses() { const res = await ...

How to format time in Node.js using PostgreSQL

I have set up two tables in my Postgres database, one called users and the other called card_info. I have implemented an endpoint for new user registration, and I have included a field named dateCreated in the code snippet below. Register.js const handle ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

Information vanishes as the element undergoes modifications

I am currently working with a JSON file that contains information about various events, which I am displaying on a calendar. Whenever an event is scheduled for a particular day, I dynamically add a div element to indicate the presence of an event on the c ...

Is there a way to access fields from an associated model within React components?

Is there a way to access fields from an associated model in React components within Rails? I have a listing model that I'm iterating through in a React component and retrieving all the fields for each record, including the ID of the associated model. ...

Determining the file path relative to the project/src directory in Node.js

Currently, in my node.js project I am utilizing log4js and aiming to include the file name where the log record was added. However, when using __filename, it provides me with the absolute path. var logger = log4js.getLogger(__filename) This results in lo ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

The compiler throwing an error claiming that the indexOf method is not a valid

Currently, I am working on a simple form that collects user input and aims to validate the email field by checking for the presence of "@" and "." symbols. However, every time I attempt to run it, an error message stating that indexOf is not a function p ...

Are promises perpetually in a state of limbo? (incorrect format

As a newcomer to node.js, express, and ES6, I am learning the ropes and trying to write cleaner, more efficient code using ES6 functions and promises. One issue I'm facing is with inherited functions and values, particularly next(). Here's the co ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...

Using the OR operator in a JSON server

One way to retrieve data from a json-server (simulated server) is by using the following call: http://localhost:3000/posts?title_like=head&comments_like=today When this call is made, records will be returned where the title is similar to "head" AND c ...

Obtain the URL for making an asynchronous request using PHP and SQL

I'm encountering some issues with a website I am attempting to update. A script named "jquery.script.js" is called in the head section containing some code. $.ajax({ url: 'function.js.php?option=urlget&id='+movie_id, ...