skip to Main Content

I am calling a function in js to replace the element labelled as ‘test’ in a HTML document, ‘test’ is just a paragraph that reads "Hello world".

function doSomething(){
    document.getElementById("test")
    .style.color = "magenta";
    .textContent = "Goodbye";

It highlights the ‘.’ before textContent, if I remove the ‘.’ the text changes colour but it still says "Hello world"

Very new to JS so ik this probably has some easy fix but I can’t find it anywhere.

4

Answers


  1. I think you have to target the element twice, or this is not your main problem?

    function doSomething(){
    document.getElementById("test")
    .style.color = "magenta";
    
    document.getElementById("test")
    

    .textContent = "Goodbye";

    Login or Signup to reply.
  2. The result of an assignment (obj.a = b) is the value that was assigned, not the object you were using (and the ; would have terminated the statement anyway). Instead, save the object reference to a variable/constant, then do two separate assignments:

    function doSomething(){
        const element = document.getElementById("test");
        element.style.color = "magenta";
        element.textContent = "Goodbye";
    }
    
    Login or Signup to reply.
  3. The issue in your JavaScript code is the placement of the period (‘.’) before .textContent. You should chain the property assignments without separating them with a period.

    function doSomething() {
        var element = document.getElementById("test");
        element.style.color = "magenta";
        element.textContent = "Goodbye";
    }
    
    Login or Signup to reply.
  4. Sounds like you’re looking for this:

    function doSomething(){
        document.getElementById("test").style.color = "magenta";
        document.getElementById("test").textContent = "Goodbye";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search