I am new to Java script. I practice the code. When I put my code in the chapter section, then I get the null element, and when I put it in the body, but before the element, I also get null, but if I put it inside the body, but after the element I I get the item. I want to ask why I get null in the case of the first two cases. Here is my code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="js/attributes.js"></script> // null </head> <body> <script type="text/javascript" src="js/attributes.js"></script> // null <a id="braingialink" onclick="return showAttributes();" href="http://www.braingia.org" >Steve Suehring Web Site </a> <script type="text/javascript" src="js/attributes.js"></script> // ok </body>
Here is my javascript
var a1 = document.getElementById("braingialink"); //get null in first two cases window.alert(a1.getAttribute("href")); a1.setAttribute("href", "www.google.com"); window.alert(a1.getAttribute("href")); function showAttributes() { var e = document.getElementById("braingialink"); var elementList = ""; for (var element in e) { /** * Sometimes, especially when first programming with JavaScript, you might not know what * attributes are available for a given element. But you don't have to worry about that, because * of a loop that calls the getAttribute() method. */ var attrib = e.getAttribute(element); elementList = elementList + element + ": " + attrib + "\n"; } //end of for() alert(elementList); } //end of function showAttributes
And also tell me by placing <script type="text/javascript" src="js/attributes.js"></script>
after the a element, this is the same as what I write the script in the script tag, for example
<a href="http://www.braingia.org" id="braingialink">Steve Suehring Web Site</a> <script type="text/javascript"> var a1 = document.getElementById("braingialink"); alert(a1.getAttribute("href")); a1.setAttribute("href","http://www.microsoft.com"); alert(a1.getAttribute("href")); </script>
Do both things mean the same thing?
thanks
Basit source share