/    Sign up×
Community /Pin to ProfileBookmark

global variables and innerHTML

I need to grab the html code between a span tag and assign it to a variable when the page first loads. Then I need to access that variable from within another function. No matter what I’ve tried I keep receiving the error “code is not defined”. I know that the code is being assigned to the variable because I’ve used the alert() command to verify it. So how can I make that variable accessible from another function?

[code]
<html>
<head>
<script>
onload = function() {
var code = document.getElementById(‘copy’).innerHTML;
alert(code);
}

function other() {
alert(code);
}
</script>
</head>
<body>
<span id=”copy”>
This is what I want to copy.
<br>
This is what I want to copy.
</span>
<br><br>
<h1 onclick=”other()”>Test the function</h1>

</body>
</html>
[/code]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@UltimaterOct 11.2005 — Simply omit [color=red]var[/color] in order to make the variable [color=royalblue][i]code[/i][/color] global.
Copy linkTweet thisAlerts:
@CharlesOct 11.2005 — Strictly speaking, and we realy should speak strictly lest we confuse ourselves down the line, there are no global variables in client side JavaScript. All "variables" are a property of some object. Inside a function, if you use the "var" key word your "variable" will be a property of the call Object and will be destroyed when the function returns. Without the "var" key word the "variable" is a property of the containing Window object. Outside a function the "var" key word does nothing.
Copy linkTweet thisAlerts:
@pccodeauthorOct 11.2005 — That was too easy. ? Thanks.
×

Success!

Help @pccode spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...