0

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???
};
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
user_78361084
  • 3,538
  • 22
  • 85
  • 147

5 Answers5

2

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

chrisbradbury
  • 327
  • 1
  • 5
  • 1
    I think it's worth mentioning that his original example alerts the div element because `window.my_div` is actually the element by ID. – Explosion Pills Jan 14 '13 at 17:18
2

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();
});
dynamic
  • 46,985
  • 55
  • 154
  • 231
2

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?

Community
  • 1
  • 1
drinchev
  • 19,201
  • 4
  • 67
  • 93
1
$(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.

Leeish
  • 5,203
  • 2
  • 17
  • 45
0

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 
Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82