+ 5
How can I get the value of a variable from a script in div element in another div element's script tag?
<div id="element1"> <script> // I want the variable's value from other div's script tag </script> </div> <div id="element2"> <script> //value of a variable is declared here </script> </div> Language: JavaScript,. Please help.
12 ответов
+ 5
Okay, I just realized you want to access a variable from element2 in element1. So we'll have to make sure not to access the variable before it's declared. Something like
<div id="element1">
<script>
function f(){
console.log(c);
}
</script>
</div>
<div id="element2">
<script>
var c=2;
f();
</script>
</div>
But I'm not sure if it would serve your needs.
+ 6
Instead of using two separate ones, is there any particular reason why we can't put the two scripts together?
Edit: it looks like the two script tags behave just as if they were one. So the normal rules should apply.
+ 6
Simple answer: The same way you would access the variable if they were in the same <script> tag.
Variables declared across separate <script> tags, or separate JS files for that matter, will ultimately share the same global scope. It will be as if they were all written into the same JS file or same <script> tag.
Also, there is no relationship between the JavaScript code in a <script> tag and the parent HTML element containing that <script> tag.
+ 6
Hi Asirbachan... I'm trying to understand what you're trying to describe.
The wording in your last post gives me the impression that you may have some confusion around the relationship between HTML tag elements and Javascript variables.
Specifically, the phrase "variable in a div" implies that <div> tags contain variables, which is incorrect.
Can you provide clarification?
+ 4
If you declare the variable in the global scope you can get it without problem in another <script> block
+ 3
Oh, for id i think
+ 2
I will try. and thanks for helping
+ 2
numerical variable. I will post my code here tomorrow. so you can understand
+ 1
ok I'm going to describe it tomorrow as now I am not free. but thanks for helping.
+ 1
David Carroll, of course I have doubt in it as I am new to js and don't know anything. All I want to tell is I want to create a button. the button will get the value of variable declared in another div element's script tag. then the button will show image according to the variable declared. hope you understand my problem.
+ 1
What are some examples of values to be expected from this variable?
0
to Kishalaya Saha : I want to create a game in which a button has to get the value of a variable in a div to act upon. so I can't put the script together.