AlienC
AlienC

Reputation: 31

Typeof operator Trouble

I have a div that has hidden text.This text can only be displayed if the text contents of another div equal a string. To do this, i wrote the function below:

function show() {
    if(typeof genDiv.innerHTML == "string") {
        showDiv.innerHTML = fullhiragana[h];
    } else {
        alert("Please generate the Romaji before requesting the Hiragana to be displayed.");
    }
}
     //fullhiragana is an array that has the data that 'showDiv' is supposed to display.
      'h' is a var that randomly picks a string from fullhiragana.//

In a way, it works. It displays the text if I press the button, but it does this regardless of the type of content in the other div. It even works if there is no content in the first div. Maybe I've constructed the if conditional wrong? Help please! see this printscreen for further reference of the problem; http://prntscr.com/5o7q59

Upvotes: 0

Views: 92

Answers (3)

James Wright
James Wright

Reputation: 3010

Building upon raneshu's answer, an empty String object resolves to a falsy value in JavaScript i.e. one could operate upon a String via type conversion to a Boolean:

if (!container.innerHTML) {
    console.log('#container has no content!');
}

See this JSFiddle for a working example.

Also, here's some information on falsy values in JavaScript, including Strings.

Upvotes: 0

garryp
garryp

Reputation: 5766

Regarding the user of innerHTML.length, this should work in modern browsers, but be aware that some older (IE) browsers may return true even when there is no text since the innerHTML property may include whitespace. You may want to clear leading and trailing whitespace before you check that condition.

Upvotes: 0

raneshu
raneshu

Reputation: 413

typeof(genDiv.innerHTML == "string") is always true. So it is true even if the div is empty or has a number or arithmetic operator like(+, &, %, -), etc...

If there is no content in the first div, genDiv.innerHTML is the empty string ("").

What you can do to check if something has been entered in to the input field is:

if(genDiv.innerHTML.length>0) {
    showDiv.innerHTML = fullhiragana[h];
}

Also, it is better to use genDiv.value instead of genDiv.innerHTML if you want to get the content of an input field.

Upvotes: 1

Related Questions