0

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>
1
  • 1
    Whenever you see a method with plural, as in getElements... and not getElement..., it gets more than one element, and you have a nodeList. Commented Mar 6, 2014 at 19:27

3 Answers 3

1

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])

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

0

Change this line

var attribute = element.getAttribute("href");

to this

var attribute = element[0].getAttribute("href");

2 Comments

actually your hint was good, but instead I did element[0].setAttribute("href","Http://google.com"); element[0].setAttribute("target","_blank");
@saharsadatjafari Ok. Just be sure to accept an answer (whichever one helped the most) by clicking the checkmark next to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.