0

I wanted to fully understand and learn JS Switch statement so I thought of an exercise for myself - to change HTML title depending on what text of a title currently exists.

Here's the JS code:

var zz = document.getElementById("title").textContent;

switch(zz) {

    case "Homepage":
        console.log(document.getElementById("title").textContent);
        document.getElementById("title").textContent = "Case 1";
        console.log(document.getElementById("title").textContent + "(HAS CHANGED)")
        break;

    case "Homepage2":
        console.log(document.getElementById("title").textContent);
        document.getElementById("title").textContent = "Case 2";
        console.log(document.getElementById("title").textContent + "(HAS CHANGED)")
        break;

    default:
        console.log(document.getElementById("title").textContent);
        document.getElementById("title").textContent = "Default case";
        console.log(document.getElementById("title").textContent + "(HAS CHANGED)")
        break;
}

HTML:

<title id="title"> Homepage </title>

Problem is that it always executes the "default" case even though the title fits of of the presented cases. I believe the problem is within the var zz = document.getElementById("title").textContent; because if I declare the text content of it - it works (I don't want to do that as it just overwrites the existing title from HTML). Is it possible to achieve this with switch statement? P.S I don't want to use if/else - I want to do it with switch. Thanks

1
  • 1
    Maybe the problem is due to extra spaces around the text - for ex., ` Homepage ` instead of Homepage? Commented Dec 28, 2020 at 10:17

3 Answers 3

1

Currently you're comparing ' Homepage ' with 'Homepage' which is a different string because of the whitespaces.

The solution is to add trim() at the end of your first line, like so:

var zz = document.getElementById("title").textContent.trim();

trim(): removes whitespace from both sides of a string

Sign up to request clarification or add additional context in comments.

Comments

1
var zz = document.getElementById("title").html().trim();

Comments

1

you can .innerHTML function :

var zz = document.getElementById("title").textContent;

switch(zz) {

    case "Homepage":
        document.getElementById("title").innerHTML = "<title id="title"> Case 1 </title>";
        break;

    case "Homepage2":
        document.getElementById("title").textContent = "<title id="title"> Case 2  </title>";
        break;

    default:
        document.getElementById("title").textContent = "<title id="title"> Default case </title>";
        break;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.