Reputation: 83
I am learning how to use JavaScript and I am having trouble correctly displaying the url within the document.write() function. I am writing the program with an actual url in the "href" portion but I can not write it in this question since it is apparently prohibited to do so. Is there something that I am missing?
<!doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Link Test </title>
</head>
<body>
<a id="mylink" href="#"> Click me</a>
<br>
<script type="text/JavaScript">
url = document.links.mylink.href document.write('The URL is ' + url)
</script>
</body>
</html>
Upvotes: 0
Views: 3653
Reputation: 1878
let url = document.links.mylink.href;
document.write('The URL is ' + link);
But still, I won't recommend using document.write
method. You'd better add some html tag, where you can safely insert the result via innerHtml
or innerText
methods:
html:
<a id="mylink" href="#Test"> Click me</a>
<span id="result"></span>
js:
let url = document.links.mylink.href;
let result = document.getElementById('result');
result.innerText = url;
Upvotes: 0
Reputation: 68635
Remove type="text/JavaScript"
part from your code. Some modern browsers will give you an error on it.
Also I suggest you to write your statements in separate lines. JS engine understands your whole line as a one statement. So it gives an error. I suggest you to separate lines and put ;
at the end of each line or you can add ;
after the statement, if you want to write in one line. And also define your variables with var
or let
and const
in ES6.
<!doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Link Test </title>
</head>
<body>
<a id="mylink" href="#"> Click me</a>
<br>
<script>
var url = document.links.mylink.href ;
document.write('The URL is ' + url);
</script>
</body>
</html>
Upvotes: 1
Reputation: 1703
You are missing a semicolon if you want to have it on one line. Like this:
url = document.links.mylink.href; document.write('The URL is ' + url);
I would however recommend putting them on two lines, like this:
var url = document.links.mylink.href;
document.write('The URL is ' + url);
..and using var
to declare url as a variable, good practice
Upvotes: 2