SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Location
    California
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Checking if a variable exists

    Why does this code check whether 'oneHref' is true or not in the beginning of the 'if' statement? I took it out and the code still preformed its function (to add an <img> to external links on page load.) So, if it still works why should it be there?

    Code:
    <script type="text/javascript">
    			function externalLinks() {
    				var allLinks = document.getElementsByTagName("a");
    				
    				var icon = document.createElement("img");
    				icon.setAttribute("src", "external.png");
    				icon.setAttribute("alt", "[external link]");
    				
    				for (var i = 0; i < allLinks.length; i++) {
    					var oneHref = allLinks[i].getAttribute("href");
                                            
                                            // here, right before the '&&'
    					if (oneHref && oneHref.indexOf("http") == 0) {
    						var newImg = icon.cloneNode(true);
    						allLinks[i].appendChild(newImg);
    					}
    				}
    			}
    			
    			window.onload = externalLinks;
    		</script>
    (code taken directly from Designing with Web Standards, 3rd Edition. Jeffrey Zeldman)

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,107
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    If there are links in the page without an href it will throw an error without it, it's just being safe.
    e.g. calling indexOf on an undefined or null object will throw an error.

    Code javascript:
    if (undefinedVariable.indexOf("http") == 0) {
     
    }

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Location
    California
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In properly marked up code all <a> tags should have an href attribute, correct? Is it legal to have an anchor tag without an href? If so, for what purpose?

    Also, what are the consequences of throwing an error? I edited the code so that it'd throw an error - and it did - but it still worked (the external link image was still placed after the links with an href attribute)


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •