Search code examples
javascripthtmlunobtrusive-javascript

javascript unobtrusive


i have an html page, which is consist of many hyperlink like this inside body tag...

<a href="http://www.example.com/?id=313354">User Name</a>

then i decide to use unobtrusive javascript ... then i'd like to change all the "a" tag to be...

<a id="354313" href=#>User Name</a>

when i click the second link above, i want that it'll call a function like the first link does,... my question is how to get all the "a" element inside body tag then apply a function depend it's id...


Solution

  • What you're after is this code:

    <script type="text/javascript">
    window.onload = function WindowLoad() {
        var arrLinks = document.getElementsByTagName("a");
        for (var i = 0; i < arrLinks.length; i++) {
            var oLink = arrLinks[i];
            var sCurHref = oLink.href;
            if (sCurHref.indexOf("?id=") >= 0) {
                var ID = sCurHref.split("?id=")[1];
                if (ID.length > 0) {
                    oLink.id = ID;
                    oLink.href = "#";
                    oLink.onclick = function() {
                        document.location.href = sCurHref;
                        return false;
                    }
                }
            }
        }
    }
    </script>
    

    This will iterate all the links, changing the visible HREF to "#" and preserving their functionality, applying the proper ID. (Though you didn't say what's the use of that ID)

    Feel free to mess around with the live test case: http://jsfiddle.net/yahavbr/uMbEY/