-4

Hello guys I would like some help since I am new to JS I expect this piece of code to show an alert with the href of the element "aaa" but nothing happens. Could you explain what I am doing wrong? thanks

<html>
<body>

<script type="text/javascript">
    function myFunction(){
        var xxx = document.getElementById("aaa").href;
        alert(xxx);
    }
    myFunction();
</script>

<a href="Moody'sKMVproject-studentsample2.doc" id="aaa">file word</a>
</body>
</html>

Please delete this question as it is a duplicate of Why does jQuery or a DOM method such as getElementById not find the element?

I am sorry for posting .. I am new to JS and I didn't know what to search for in the first place

gioxc88
  • 348
  • 1
  • 15

4 Answers4

1

The problem is that your script is executed before the a tag is rendered. Put the script tag after the a tag and it should work.

Patrick Hund
  • 14,392
  • 8
  • 50
  • 77
  • thanks ... it worked like a charm. Nevertheless I saw many examples with script that refers to tags that are put after the script – gioxc88 Sep 30 '17 at 12:23
1

The script is executed before the DOM is ready so there is no element with id aaa. You can add the script inside

window.load=function(){
function myFunction(){
        var xxx = document.getElementById("aaa").href;
        alert(xxx);
    }
    myFunction();
}

You can also define the script tag near closing body tag. In this case the DOM is ready and it will able to find an element with id

<body>
<a href="Moody'sKMVproject-studentsample2.doc" id="aaa">file word</a>

<script type="text/javascript">
    function myFunction(){
        var xxx = document.getElementById("aaa").href;
        alert(xxx);
    }
    myFunction();
</script>
</body>
brk
  • 43,022
  • 4
  • 37
  • 61
1

First of all, you should use Developer Console for finding errors (right click page, then Inspect Element).

Anyway, the problem seems to be that your JavaScript is done before you have made the anchor (a) element.

<html>
<body>
<a href="Moody'sKMVproject-studentsample2.doc" id="aaa">file word</a>
<script type="text/javascript">
    function myFunction(){
    var xxx = document.getElementById("aaa").href;
    alert(xxx);
}
myFunction();
</script>
</body>

This should work.

Steve Woods
  • 217
  • 1
  • 9
-1

Just as Patrick said, move the tag down after and I think this value of href is what you looking for

var xxx = document.getElementById("aaa").getAttribute("href");
Loredra L
  • 1,289
  • 1
  • 13
  • 27