modify the class's CSS style

Hey there! I'm having an issue with my code snippet. My goal is to change the background color of both fields with the class 'navicon', as shown in the function fu(). However, it's not working as expected. Changing the color based on id is fine, but I prefer not to give each button a specific id. Any ideas on what I might be doing wrong? Thanks!

<!DOCTYPE html>
<html>
    <head>
          <meta charset="UTF-8">
<!        <link rel="stylesheet" href="css/navside.css" type="text/css">
          <style>
.navside {
    list-style-type: none;
        margin: 0;
        padding: 0;
    overflow: hidden;
    background-color: #333;
    }

.navside a {
    float: center;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    }

.navside a:hover {
    background-color: #ddd;
    color: black;
    }

</style>
</head>
<body>

<script>    
function fun(){
    document.getElementById("demo").style.backgroundColor="red";

    function fu(){ 
        var all = document.getElementsByClassName('navicon');
        for(var i=0;i<all.length;i++){
            all[i].style.backgroundColor='red';
        }
    }
}
</script>

<div class="navside">
    <a class="navicon" id="demo" href="#bla" onclick="fun()" >Text1</a><br>
    <a class="navicon"  href="#blubb" onclick="fu()">Text2</a>
</div>
</body>
</html>

Answer №1

One issue is that the definition of fu() is placed within fun(), making it inaccessible from the global scope. There appears to be no reason for it to be a local function, indicating this was likely an error. It would be best to define both functions globally.

function fun(){
    document.getElementById("demo").style.backgroundColor="red";
}

function fu(){ 
    var all = document.getElementsByClassName('navicon');
    for(var i=0;i<all.length;i++){
        all[i].style.backgroundColor='red';
    }
}

An indication of this issue could have been seen in the error message within the Javascript console stating that the function fu is not recognized.

Answer №2

const changeColor = () => {
    document.getElementById("demo").style.backgroundColor = "blue";
}

Instead of using a for loop, the same effect can be achieved with the help of querySelectorAll.

const changeBgColor = () => { 
    document.querySelectorAll('.navicon')
        .forEach((element) => { element.style.backgroundColor = 'blue' });

}

Answer №3

You are attempting to invoke a non-existent function

The proper way to handle this is:

Accessing the length within a loop is not recommended

function fun(){
    document.getElementById("demo").style.backgroundColor="red";
}
function fu(){ 
    var all = document.getElementsByClassName('navicon'),
        len = all.length,
        i;
    for(i=0;i<len;i+=1){
        all[i].style.backgroundColor='red';
    }
}

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

Ensure the text value of a collection of web elements by utilizing nightwatch.js

Recently, I started using nightwatch.js and I am trying to retrieve a list of elements to verify the text value of each element against a specific string. Here's what I have attempted: function iterateElements(elems) { elems.value.forEach(funct ...

Surprising block of text suddenly popped up on the browser screen while I was in the middle of working on

Currently delving into the world of MERN stack and working on a simple project. Everything was going smoothly on localhost until out of nowhere, some garbled text appeared on the screen, hindering my progress. I'm completely stumped as to what this my ...

Having Trouble Changing CSS with Rails Link_to CSS ID

While following the ruby on rails guide, I came across a specific way to write link_to's with a css id: <%= link_to "About", about_path, id: "third" %> I also attempted: <%= link_to ("About", :id => "third"), about_path %> Although ...

Error message: "Angular dependencies and provider not accessible"

I recently came across a file upload script on Github that I decided to implement. <script type="text/javascript" src="{% static 'bower_components/angular-file-upload/angular-file-upload.min.js' %}"></script> Furthermore, I have cre ...

Bringing packages from around the world into your Node.js project

In my node.js application, I have several modules where I find myself importing the same package (e.g. moment npm). I'm curious if there is a more efficient way to handle imports by centralizing all dependencies in one place and using them as global ...

Problem with updating an Html.TextBoxFor based on the value of another one

I have been trying to implement a basic jQuery functionality that involves changing the text in one textbox to be half of the numeric value entered in another textbox. Below is the script I am using: <script> $(document).ready(function () { $(& ...

Update the query string to accommodate several values

Having an issue with my query string. Whenever multiple values are selected, my Django search function malfunctions. The URL displays ?Query=value1&Query=Value2, but only the last value is actually searched. I need both values to be searched using an A ...

Execute a JavaScript file stored in the filesystem using Selenium

Having trouble running a YUI js script using js.executeScript Selenium method. The script is being executed by Selenium Webdriver to simulate a "click" on a hybrid mobile app (the button is in a webview). String IncludeYUI = "script = document.createElem ...

get a duplicate of an object

Is this the proper method for creating a duplicate of an object? class ObjectWrapper { private _obj; /*** * Copy object passed as argument to this._obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of this._ ...

Background image color not displaying correctly

I've been attempting to overlay a transparent color on top of a background image. While the background image is displaying correctly, I'm having trouble getting the color to show up. I noticed that this question has been asked before. I tried im ...

Determine the moment when jQuery's load() function completes the loading of several images

My script utilizes jQuery's getScript() function to dynamically retrieve blog posts from Tumblr accounts. The response from the script is a JSON structure called tumblr_api_read, which includes image URLs among other things. function read(blogName) ...

The function Amplify.configure does not exist

Currently attempting to utilize AWS Amplify with S3 Storage, following the steps outlined in this tutorial for manual setup. I have created a file named amplify-test.js, and here is its content: // import Amplify from 'aws-amplify'; var Amplify ...

What is the best way to monitor a document variable that is set after a component has been

Is there a way to access the variable document.googleAnalytics, added by Google Tag Manager, for A/B testing on a Vue.js page? I attempted to initialize the variable in both the mounted and created methods of the component, but it returns as undefined: ex ...

Error in React Typescript Order Form when recalculating on change

When creating an order form with React TypeScript, users can input the quantity, unit price, and select whether the item is taxable. In this simplified example, only 1 or 2 items can be added, but in the final version, users will be able to add 10-15 item ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

npm ERR! Your operating system has denied the operation

When attempting to install create-react-app globally using 'npm install -g create-react-app', an error occurred due to insufficient write access to the /usr/local/lib/node_modules directory. The error message displayed was as follows ...

``I am having trouble getting the Bootstrap carousel to start

I am having trouble getting the Bootstrap Carousel to function as expected. Despite including all the necessary code, such as initializing the carousel in jQuery.ready, the images are stacking on top of each other with navigation arrows below them instea ...

Can the minimum length be automatically filled between two elements?

I'm struggling to find a way to adjust the spacing of the "auto filling in" dots to ensure a minimum length. Sometimes, on smaller screens, there are only one or two dots visible between items. Is there a way to set a minimum length for the dots in th ...

Maintain the default material-ui class styles while making customizations to override others

Currently, I am working on customizing the material-ui tooltip and specifically need to adjust the margin for the tooltipPlacementTop class: const useStyles = makeStyles(theme => ({ tooltipPlacementTop: { margin: '4px 0' ...

What is the best way to set unique heights for various ion-grid components?

Situation: I am facing an issue with my Ionic/Angular app. The screen layout, as shown in the image provided and on Stackblitz, includes two ion-grids with different background colors - green and red. Goal: My goal is to assign a percentage height to each ...