Using JavaScript to override a specifically declared CSS style

In the process of working with a database, I come across HTML that includes "spans" colored in different shades. An example would be:

<div id="RelevantDiv">the industry's standard <span style="background-color: red">dummy text ever since the 1500s, when an unknown printer took a galley</span> of type and scrambled it to make a type specimen book. It has survived not only five.</div>

While I want to maintain this coloring, I also aim to create a JavaScript function that can toggle the background color on or off. I attempted the following approach:

function HLtoggle()
{
var element = document.getElementById('RelevantDiv');
element.style.background = '#FFFFFF';
}

Unfortunately, this method doesn't work as the spans are obviously overriding the styling.

Answer №1

The style for the background-color is set on the span element, while in your JavaScript code you are targeting the parent div.

To fix this issue, you can try the following:

var element = document.querySelectorAll('#RelevantDiv > span')[0];
element.style['background-color'] = '#FFFFFF';

Alternatively, I recommend giving a class name to your highlighted span and selecting it by that class instead of by the tag name.

Answer №2

If you want to change the color of a span element, you can achieve this by using the following code snippet:

var targetElement = document.getElementById('RelevantSpan');
targetElement.style.background = '#FFFFFF';

Make sure to assign an id to the span element in order to specifically target it, like so:

<span id="RelevantSpan" style="background-color: red">

The code you provided for wrapping it up in a function is correct, but don't forget to call that function using an appropriate event handler if you want it to trigger at certain times.

Check out this jsfiddle example demonstrating how to call the function when you mouse over the span:

https://jsfiddle.net/oLfyx0h5/4/

Answer №3

Instead of selecting the span, you're currently pointing at the div which is why the css isn't being overridden. Give this a try:

<div id="RelevantDiv">the standard in the industry <span id='another_span_id' style="background-color: blue">...

Update the function like so:

function changeColor() {
    var newElement = document.getElementById('another_span_id');
    newElement.style.backgroundColor = '#FFFF00';
}
changeColor()

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

What is the best way to get both the id and name of a selected item in Angular?

Within my select field, data is dynamically populated based on names. My objective is to not only capture the selected name but also its corresponding ID. Here's a snippet of my HTML template: <select class="custom-select d-block w-100" id="test" ...

Pairing Symfony2 with the power of jQuery AJAX

When developing an application with Symfony2 and using Jquery as a JavaScript FW along with Twig templates, I encountered the need to pass selected tag values from the template back to the controller upon submission. After rendering a template from the con ...

What could be the reason behind Google and Bing's mobile-friendly tests inaccurately flagging my site as non-mobile friendly?

Our website for resources is responsive and has been thoroughly tested on various real smartphones, including iPhone, Android, and Windows devices. It looks great on every phone we've tested it on. You can visit the resources website here: The site ...

Substituting characters, backslashes, and double quotes may not function properly

Trying to replace a single backslash \ with two \\, but encountering issues with double quotes. var json = { "DateToday": "2021-08-11", "MetaData": [ { "id": "222" ...

Comparing Redux with passing state down to components as props from the top level of the application

With limited experience in react-redux, I am currently working on a smaller web-based application intended for around 100 users. At this time, I have opted not to use redux due to concerns about its complexity for such a small project. Instead, I have been ...

Navigation bar at the bottom using Twitter Bootstrap 3 that includes a combination of full-width and regular containers

I've been tasked with recreating the designer's layout using Bootstrap. The desired layout consists of two full-width bars and a fixed container for the main content and footer menu. I have successfully implemented this layout, including respons ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Having trouble with properly writing to multidimensional arrays?

The issue I am encountering is clearly depicted in the simplified code snippet below. During the execution of the TestArrays function, the goal is to write a single item to each location in the multidimensional array. However, upon examining the layers in ...

What is the accurate way to determine the total number of minutes elapsed from a specific point in time?

String representation of the process start date: '2020-03-02 06:49:05' Process completion date: '2020-03-02 07:05:02' Question: What is the optimal method for calculating the time difference (in minutes) between the start and end ...

Module specifier "vue" could not be resolved due to an uncaught TypeError. Remember that relative module specifiers must always begin with "./", "../" or "/"

Looking to create the most basic vuejs Hello World application using separate files. Here is the project setup: start by creating index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Encountering an issue of THREE.EventDispatcher being undefined while trying to create a THREE.OrbitControls instance using THREE.js, THREE.OrbitControls, and TypeScript

Attempting to delve into typescript alongside three.js, I've encountered a perplexing error that has me stumped. The root of the issue lies within the init function where I initialize a new THREE.OrbitControls controller. Utilizing the setup provided ...

Is the eval() function initially used to directly translate the evaluated string?

Try running this code snippet in your browser: eval("(function() { console.log(JSON.parse('" + JSON.stringify('THIS IS COOL') + "')); })()"); It will output THIS IS COOL, however, if you run the following: eval("(function() { console ...

The modal feature is malfunctioning on a dynamic Flask website across all web browsers

I've encountered a peculiar issue while developing a Flask website that involves the functionality of a Bootstrap modal. This problem is consistent across different browsers like Firefox, Chrome, and Safari. On the main route of my website, users can ...

Accordion - Conceal Previously Revealed Items

I'm currently working on finding a solution to hide all child sections that are open in my accordion when a new header is clicked. I've included a jsfiddle link to show what I have so far. Any suggestions on how to close the opened sections would ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

Store the link in a variable and retrieve its content into another variable

Is there a way to extract the content of a link stored in a variable and store it in another variable using jQuery or javascript while working on an XML page? I know this is possible with php, but since I am developing a Chrome extension, I am wondering ...

I am looking to retrieve the values entered in a textbox from an HTML document and then post them using a JSON file in Node.js when the submit button is

Here is the JavaScript code I have written: $(document).ready(function(){ $('form').on('submit', function(){ var email = $("form input[type=text][name=emails]").val(); var todo = {email: email.val(), ...

The issue with the Angular custom checkbox directive arises when using it within an ng-repeat

A personalized directive has been developed for checkboxes that is applicable throughout the application. The code for creating the checkbox is as follows: JS angular.module("myApp") .component("ngCheckbox", { template: '<di ...

Issues with closures in JavaScript

Struggling to grasp closure with 3 levels of scopes. https://jsfiddle.net/Ar2zee/wLy8rkyL/1/ How can I retrieve the value of parameter "g" within the level3 function? var a = 10; function level1(b) { var c = 1; function level2(f) { var d = 2 ...

The texture of the dodecahedron is nowhere to be found

I've been experimenting with ThreeJS to construct a dodecahedron and apply a texture to each face. I'm also utilizing Raycaster to identify which face is being clicked on. While everything works smoothly for a cube, I encounter issues when attem ...