Reputation: 41
I am trying to get a link to change javascript innerHTML everytime it is clicked.
function id_1(a){
var id = document.getElementById(a);
if (id.innerHTML==="innerHTML2"){
id.innerHTML="innerHTML1";
}
if (id.innerHTML==="innerHTML1"){
id.innerHTML="innerHTML2";
}
}
<a id="id" href="javascript:id_1('id')">innerHTML1</a>
I want it to change from innerHTML1
to innerHTML2
to innerHTML1
to innerHTML2
and so on as you click the link.
Right now it is only switching one time from innerHTML1
to innerHTML2
Upvotes: 1
Views: 1297
Reputation: 2823
You need to use else if
for the second if statement.
The logic in your code works like the following on the second click (when the content is innerHTML2):
So the solution should look like the following:
function id_1(a){
var id = document.getElementById(a);
if (id.innerHTML=="innerHTML2"){
id.innerHTML="innerHTML1";
}else if (id.innerHTML=="innerHTML1"){
id.innerHTML="innerHTML2";
}
}
To emphasize the point you could keep the code the same way but use return to make sure that only one if statement is used.
function id_1(a){
var id = document.getElementById(a);
if (id.innerHTML=="innerHTML2"){
id.innerHTML="innerHTML1";
return;
}
if (id.innerHTML=="innerHTML1"){
id.innerHTML="innerHTML2";
return;
}
}
Upvotes: 4
Reputation: 437
It actually is swithing all the times, but as you have it written, it switches to "innerHTML1" and then right back to "innerHTML2"
so just change the second "if" to "else if"
<html>
<head>
<script>
function id_1(a){
var id = document.getElementById(a);
if (id.innerHTML==="innerHTML2"){
id.innerHTML="innerHTML1";
}
else if (id.innerHTML==="innerHTML1"){
id.innerHTML="innerHTML2";
}
}
</script>
</head>
<body>
<a id="id" href="javascript:id_1('id')">innerHTML1</a>
</body>
</html>
Upvotes: 1
Reputation: 15335
You are just missing an else:
<html>
<head>
<script>
function id_1(a){
var id = document.getElementById(a);
if (id.innerHTML==="innerHTML2"){
id.innerHTML="innerHTML1";
}
else if (id.innerHTML==="innerHTML1"){
id.innerHTML="innerHTML2";
}
}
</script>
</head>
<body>
<a id="id" href="javascript:id_1('id')">innerHTML1</a>
</body>
</html>
Fiddle: http://jsfiddle.net/WCgAS/
Upvotes: 1
Reputation: 71384
You just need to use an else
between your if
statements:
function id_1(a){
var id = document.getElementById(a);
if (id.innerHTML==="innerHTML2"){
id.innerHTML="innerHTML1";
} else if (id.innerHTML==="innerHTML1"){
id.innerHTML="innerHTML2";
}
}
Without the else
your second if
is impacted by changes made in the first if
.
Since the innerHTML has only two states, you could actually simplify to:
function id_1(a){
var id = document.getElementById(a);
if (id.innerHTML==="innerHTML2"){
id.innerHTML="innerHTML1";
} else {
id.innerHTML="innerHTML2";
}
}
Upvotes: 3