Reputation: 3
I am fairy new in learning JavaScript , I am practising to manipulate a tag, here is my code I know that I am making a silly mistake here but I am not sure which part has went wrong ? could any one please give me some hint ?
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Hyperlinks
</title>
</head>
<body>
<h1>
HTML Hyperlinks
</h1>
<p>
Here is a link to <a name = "hyper" href="http://yahoo.com/">page</a>.
The text around the link is not part of the link.
</p>
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
</body>
</html>
Upvotes: 0
Views: 42
Reputation: 2788
You are requesting a collection of a tags, but then treating them like a single entity.
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
try this
<script>
var element = document.getElementsByTagName("a")[0];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
or
<script>
var elements = document.getElementsByTagName("a");
for(var i = 0; i < elements.length; i++)
{
var element = elemenets[i];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
}
</script>
Upvotes: 1
Reputation: 4769
Change this line
var attribute = element.getAttribute("href");
to this
var attribute = element[0].getAttribute("href");
Upvotes: 0
Reputation: 943605
getElementsByTagName
says elements. Plural.
It returns a NodeList, which is like an Array, not a single Element.
You need to loop over its return value (e.g. with for
) or access it by index ([0]
)
Upvotes: 1