Reputation: 148
I'm new to Javascript and HTML. I have a little problem that I've been trying to fix but don't know how.
I'm trying to pass a variable from a method in a Javascript file into a HTML file, and use its value as if it were HTML code. I know that the Javascript file is passed correctly into the HTML, the problem is just getting the variable from it.
Here is the relevant Javascript method:
function getCode() {
var myCode ="Hello World";
document.getElementById("myCode").innerHTML = "<a>" + myCode + "</a>";
}
And here is the relevant HTML code:
<body>
<a href="myCode" onclick="getCode()">
<code id="myCode" class="prettyprint"> myCode </code>
</body>
I don't know if I am doing it correct. I simply need the variable myCode to be turned into just HTML code, in other words myCode in the HTML should be turned to "Hello World" at this point:
<code class="prettyprint"> myCode </code>
Upvotes: 2
Views: 216
Reputation: 318182
Should work just fine, but setting a href value means the anchor redirects when clicking it.
<a id="myCode" href="#" onclick="getCode()">click</a>
<code id="myCode" class="prettyprint"> myCode </code>
<script>
function getCode() {
var myCode ="Hello World";
document.getElementById("myCode").innerHTML = "<a>" + myCode + "</a>";
}
</script>
Upvotes: 2
Reputation: 835
Here's a JSFiddle that works: http://jsfiddle.net/bGQy5/
<body>
<a href="#" onclick="getCode()">Click me</a>
<br/><br/>
<code id="myCode" class="prettyprint"> Text
<a href="#">Test</a>
</code>
</body>
window.getCode = function () {
var myCode = "Hello World";
document.getElementById("myCode").innerHTML = "<a>" + myCode + "</a>";
}
Please note a few issues though:
Upvotes: 1
Reputation: 63442
When clicking the link, the browser will change the address bar to myCode
, because that's what the anchor's href
attribute points to.
I'm guessing this is not what you wanted, so you can change the value of the href
attribute to something like #
to prevent this from happening.
<a href="#" onclick="getCode()">
Upvotes: 2