The solution for getting the href/src attribute (relative path 0 value) in IE6/7 is different from other browsers
The test code is as follows:
<a href="/abc/index.html">home</a> <img src="http://files.jb51.net/upload/201108/20110828174815833.gif"> <script> var link = document.getElementsByTagName('a')[0]; var img = document.getElementsByTagName('img')[0]; alert(link.getAttribute('href')); alert(img.getAttribute('src')) </script>
There are elements a and img (Standard document mode), the relative path is set as follows:
IE6/7: Return the full path
IE8/9/10/Firefox/Safari/Chrome/Opera: Return relative path
If you want to be consistent with other browsers in IE6/7, you can set the second parameter of getAttribute to 2. The standard getAttribute method does not define a second parameter. The magic of IE is as follows: MSDN's description of the setAttribute parameter
<a href="/abc/index.html">home</a> <img src="http://files.jb51.net/upload/201108/20110828174815833.gif"> <script> var link = document.getElementsByTagName('a')[0]; var img = document.getElementsByTagName('img')[0]; alert(link.getAttribute('href', 2)); // 注意第二个参数 alert(img.getAttribute('src', 2)); // // 注意第二个参数 </script>