Brslv
Brslv

Reputation: 3

Strange behavior - getElementById()

I'm currently working on something simple - a JavaScript script that makes some minimal validation if a string is an email.

But a problem occurred and I can't seem to understand it.

I have an input text field, where the user enters an email, a button, which when clicked, get's the string from the input and displays it in a div with a green background, if valid, or a red one - if invalid.

So, I have made a function get(), which simply does return a DOM element with on given id. Nothing fancy, but the strange thing comes next.

When I try to use an element, which I've 'got' from the DOM with this function in a callback function, I simply can't. But when in the callback function I manually get it with document.getElementById('status'), it works.

I don't understand where is the problem.

Here's my Html:

<section>
    <input type="text" name="email" placeholder="Enter an email" id="input" />
    <input type="submit" value="Validate &rarr;" id="submit" />
    <div class="status" id="status"></div>
</section>

And here's the JS:

var get = function(id) {
    return document.getElementById(id);
};

var input   = get('input'),
    status  = get('status'),
    btn     = get('submit');

btn.addEventListener('click', function(){
    // doesn't work
    status.innerHTML = 'Checking...';

    // works?!
    // Puts 'Checking' text in div#status
    document.getElementById('status').innerHTML = 'Checking...';
});

Upvotes: 0

Views: 171

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388446

It is a bit nasty problem where a global variable with name status won't take non string values... if you try to assign one then it will take the toString() value of that object(have tested in chrome).

In your console if you log the value of status you should get [object HTMLDivElement] which is the toString() implementation of Element object.

Just rename the variable and you should be fine

var get = function(id) {
    return document.getElementById(id);
};

var input   = get('input'),
    status1  = get('status'),
    btn     = get('submit');

btn.addEventListener('click', function(){
    // doesn't work
    status.innerHTML = 'Checking...';

    // works?!
    // Puts 'Checking' text in div#status
    document.getElementById('status').innerHTML = 'Checking...';
});

The same is true for other key window properties like name

Upvotes: 1

Mathieu Bertin
Mathieu Bertin

Reputation: 1624

You should put this code

window.onload = function() { 
 var input   = get('input'),
     status  = get('status'),
     btn     = get('submit'); 

 btn.addEventListener('click', function(){
    // doesn't work
    status.innerHTML = 'Checking...';

    // works?!
    // Puts 'Checking' text in div#status
    document.getElementById('status').innerHTML = 'Checking...';
 });
};

it should work.

Upvotes: 0

Related Questions