user_78361084
user_78361084

Reputation: 3898

Why does my variable change values?

I have a simple jsfiddle where I get the value of a div.

In the $(document).ready(function(){}) section I get the text of the div just fine. When I try to use that value later on in a function, the value changes (unless I add .innerHTML). Why does the value of that variable change? In other words, why do I need to add .innerHTML when I call that variable later on?

thanks!

<div id="my_div">1</div>

// Javascript/JQuery

$(document).ready(function(){ 
    var my_div = $("#my_div").text();

        alert(my_div);

        func();
    });


function func(){    
    alert(my_div); // why does the value change here...why???
        alert(my_div.innerHTML); // why do I need ".innerHTML' here???
};

Upvotes: 0

Views: 154

Answers (5)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

That's because all elements with ID's are properties of the global scope by default.

So basically my_div in your function func() is the same as calling window.my_div.

Try removing var my_div = $("#my_div").text() and you'll still be able to use it in func().

This question is related Do DOM tree elements with ids become global variables?

Upvotes: 2

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

When you do the following:

function func(){    
    alert(my_div); // why does the value change here...why???
    alert(my_div.innerHTML); // why do I need ".innerHTML' here???
};

You get an html element by it's id (my_div).
Why ? Because my_div ins't declared as global.
That's why when you alert you get an object.

Try to run your code using other name to my_div, like:

$(document).ready(function(){ 
    var div = $("#my_div").text();

    alert(my_div);

    func();
});


function func(){
    alert(div);
    alert(div.innerHTML);
};

You will see that you get the following error:

Uncaught ReferenceError: div is not defined 

Upvotes: 0

Leeish
Leeish

Reputation: 5213

$(document).ready(function(){ 
var my_div = $("#my_div").text();

    alert(my_div);

    func(my_div);
});


function func(my_div){    
    alert(my_div); // why does the value change here...why???
};

You need to pass in reference to my_div.

Upvotes: 1

dynamic
dynamic

Reputation: 48091

Because you declare my_div not in the global scope.

You should do like this:

var my_div;
$(document).ready(function(){ 
    my_div = $("#my_div").text();

    alert(my_div);

    func();
});

Upvotes: 2

chrisbradbury
chrisbradbury

Reputation: 327

The value changes because you aren't requesting any specific 'feature' of the div. You're just trying to alert an element...

In the first bit, you have assigned my_div inside the function. If you move the var my_div to outside the function, it becomes a global variable as opposed to a local one.

Edited fiddle: here

Upvotes: 2

Related Questions