JDestiny
JDestiny

Reputation: 1

Javascript Text Change Not Changing ID

I have an onclick javascript function that's goal is to change the text of a table to something else

function functionL1() {
    if (document.getElementById("A1").innerHTML = "Text 1" ) {
        var Transfer1 = document.getElementById("B1 ").innerHTML;
        document.getElementById("A1").innerHTML = Transfer1;
}

This works but I want to make it so the same text only appears once

Unfortunately this doesn't work

function functionL1() {
    if (document.getElementById("A1").innerHTML = "Text 1" ) {
        var Transfer1 = document.getElementById("B1 ").innerHTML;
        document.getElementById("A1").innerHTML = Transfer1;
    }
    else if (document.getElementById("A2").innerHTML = "Text 1" ) {
        var Transfer2 =  document.getElementById("P1").innerHTML;
        document.getElementById("A2").innerHTML = Transfer2;
    }
}

I think this is because after changing A1 to B1 the javascript function doesn't recognise that A1 no longer is Text 1.

Does anyone know a way around this.

Note: Replacing innerhtml with value doesn't work

Upvotes: 0

Views: 152

Answers (1)

SidOfc
SidOfc

Reputation: 4584

As said in the comments by @Gerald Schneider,

You're using an assignment operator (=) instead of a equality operator (== / ===). This is definitely one of your problems.

Another one might be that your cells don't contain just text but also some markup maybe? If this is the case and you looked over it then the value of .innerHTML will be different than the things you see.

There is also a property in JS called .textContent <- (MDN)

If you replace .innerHTML with .textContent you should atleast only get the text back without the HTML even tho it might still be different.

Last but not least, 99.9% of all issues are related to something you did not expect to be the output of a function and JS is weird in that way.

To be sure that you're getting the correct value use console.log() <- (MDN) this will log output of variables, functions and pretty much anything else you throw at it in the JS console within Dev Tools (On windows often accessed by F12 and on OSX cmd + shift + i)

Log the variables and use a (strict) equality operator instead of an assignment operator and tell us what kind of errors you're getting.

One last thing, when using an if () { ... } else if () { ... } block the
else if () { ... } will only run when the first if () { ... } evaluates to false. Make sure you keep that in mind when thinking about the logic of your program e.g. Do I want these checks to be linear or asynchronous?

Hope it helps!

Upvotes: 2

Related Questions