Reputation: 31
I have made a basic javascript if
statement but it does not seem to work. It doesn't replace the text in the Span 'box', but does without the if statement.
Here's my code:
function show() {
var span1 = document.getElementById("box").innerHTML;
if (span1 == 'asdf') {
document.getElementById("box").innerHTML = 'test';
}
}
<span id = 'link'>
<a onclick = 'show()' href = 'javascript:void(0);'>Show</a>
</span>
<span id = 'box'>
asdf
</span>
Any suggestions?
Upvotes: -1
Views: 93
Reputation: 35950
The string you're testing contains some whitespace (i.e. spaces, line breaks, tabulations) as well as the desired string.
You can remove the unnecessary whitespace characters when comparing:
if (span1.replace(/\s/g, '') === 'asdf') {
Note: Of course be careful when using regular expressions. For instance, the above condition would also pass for strings like " as df ". So you might want to improve upon that a bit.
Another solution would be to use String.prototype.indexOf()
:
if (span1.indexOf('asdf') >= 0) {
You can also use String.prototype.match()
with an appropriate regular expression:
if (span1.match(/asdf/)) {
Edit: Also, if IE8 compatibility if not a concern for you, as suggested by @ungalcrys, you might consider using String.prototype.trim()
.
Side note: consider using .textContent
instead of .innerHTML
. See this MDN page for some more info.
Upvotes: 4
Reputation: 5610
It is because the innerHtml contains 2 new line characters at the begin and end of the span1
variable
just after
var span1 = document.getElementById("box").innerHTML;
try and add:
alert('|' + span1 + '|');
and you will se exactly what I am refering about.
You could use span1.trim()
to remove the whitespace before and after that string in JS.
Upvotes: 1