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???
};
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_divto outside the function, it becomes a global variable as opposed to a local one.Edited fiddle: here