-1

I´m trying to change the color of the background (body) and some elements' text color. I want to do this by adding an "onclick" in a link from the header (the link with the class "list-3").

For the elements, I added the class "textClass" in the HTML elements I want the change to happen, and in the function I did "var textClass = document.getElementsByClassName("textClass");".

When I click on the link, nothing happens. Can anyone help me pls? I´m new to JS, so I want to keep this as simple as possible.

function changeColor(bgColor, textColor) {

    var textClass = document.getElementsByClassName("textClass");

    document.body.style.background = bgColor;
    document.textClass.style.color = textColor;
};
<!DOCTYPE html>
<html>
<head>
    <title>Stuff</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Anton%7CMontserrat%7COpen+Sans%3A300%2C300i%2C400%2C400i%2C600%2C600i%2C700%2C700i%2C800%2C800i%7CPT+Sans%3A400%2C700&amp;ver=4.0.31" type="text/css" media="all">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="css/styles.css">

    <script src="JS/main.js"></script>

</head>


<body>

    <header id="mainHeader">

        <div class="page-logo-nav">

            <div class="header-logo">

                <a href="index.html">
                
                    <img src= "img/logo.jpg">

                </a>
            
            </div>


            <div class="header-nav">

                <nav>

                    <ul>
                        <li class="list-1"><a href="index.html">SOBRE</a></li>
                        <li class="list-2"><a href="contactos.html">CONTACTOS</a></li>
                        <li class="list-3"><a style="cursor: pointer;" onclick="changeColor(yellow, red)">TEMA ESCURO</a></li>
                    </ul> 
            
                </nav>

            </div>

        </div>

    </header>


    <main>
        
        <div id="top" class="bio-image" style="background-image: url('img/allen-01.jpeg'); width: 100%; height: 99vh;">

            <div class="bio-headings">
                
                <h1>ALLEN HALLOWEEN</h1>

                <h2>BIOGRAFIA</h2>

            </div>

        
           <a href="#info" class="go-content textClass">

            <span class="arrow">&#10095;</span>

           </a> 
                
            
        </div>


        <br>
        <br>
        <br>


        <div id="info" class="info-main">
                

                <div class="info-left">

                    <h2>TUDO NO HALLOWEEN É ÚNICO...</h2>

                    <br>

                    <p class="textClass">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin et justo a enim auctor bibendum vitae sed lectus. Phasellus sit amet odio quis felis.</p>
                    

                </div>



                <div class="info-right">

                    <p class="textClass">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ultrices, velit id volutpat varius, lectus neque sagittis est, sit amet sodales dui odio at neque. Nunc aliquam volutpat quam, eu tincidunt quam bibendum sagittis. Nam accumsan nisi eu viverra commodo. Pellentesque ut ornare.</p>

                    <br>

                    <p class="textClass">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque dictum volutpat molestie. Cras ac semper metus. Quisque eget quam eget orci vulputate condimentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse eu.</p>

                </div>
doo_doo_fart_man
  • 394
  • 3
  • 11
DGF
  • 330
  • 1
  • 4
  • 11

1 Answers1

1

This bit

var textClass = document.getElementsByClassName("textClass");

gives you "an array-like object of all child elements" (MDN).

So essentially there's two mistakes here:

  • textClass is not the class, but all elements with that class within document, in an array-like structure. A better name would be something along the lines of textClassElements.
  • You've defined that variable in your scope – it's not a property of document.

I'd recommend working with querySelectorAll since it's easier to handle and attach a JS event listener instead of modifying the onclick property (which is discouraged).


function changeColor(bgColor, textColor) {

    document.body.style.background = bgColor;
   
    var textClassElements = document.querySelectorAll('.textClass');
    textClassElements.forEach(function(element) {
       element.style.color = textColor;
    });
}

var trigger = document.querySelector('.list-3') // will only select the first element matching the selector
trigger.addEventListener('click', function() {
  changeColor('#ff0', '#f00');
});

within your function should do the trick.


Additional reading:

  • Thank you. But it still isn´t working. Maybe a problem in the html? Now I have my JS like this: `function changeColor(bgColor, textColor) { var textClassElements = document.getElementsByClassName("textClass"); document.body.style.background = bgColor; textClassElements.forEach( function(element) { element.style.color = textColor; }); }; ` – DGF Dec 22 '20 at 19:35
  • @epascarello yeah, I noticed now, I needed to add ' ' in "changeColor('yellow', 'red')". But it´s not working completly. It´s only changing the background color, the text color is not changing. Any suggestion? – DGF Dec 22 '20 at 19:42
  • I´m getting an error in the console log saying: Uncaught TypeError: textClassElements.forEach is not a function at changeColor (main.js:26) at HTMLAnchorElement.onclick (VM838 index.html:43). Can´t figure it out, I´m still new to this... – DGF Dec 22 '20 at 20:06
  • 1
    I've updated my answer – the `HTMLCollection` returned by`getElementsByClassName` is not _that_ much like an array – it does not contain the `forEach` method. – Mr. Mediocre Dec 22 '20 at 20:27
  • Figured it out. Did like this: for (var i = 0; i < textClassElements.length; i++) { textClassElements.item(i).style.color = textColor; }. Saw in here: https://stackoverflow.com/questions/15843581/how-to-correctly-iterate-through-getelementsbyclassname/39146365 – DGF Dec 22 '20 at 20:29
  • @Mr.Mediocre Thanks for the help! I solved it with this post: https://stackoverflow.com/questions/15843581/how-to-correctly-iterate-through-getelementsbyclassname/39146365. It´s because getElementsByClassName doens´t retrieve an array but a NodeList. Dont´t know the difference but yeah... – DGF Dec 22 '20 at 20:34