Adding Anchor to a text on the fly using jQuery

Adding Anchor to a text on the fly using jQuery

I come across the requirement where I need to create an anchor to a list based on some condition – hence I can go that specific anchor right away.

Though this can fairly and easily performed from the server side while the list is being prepared – without a bandwidth problem, I have found javascript method more fancy and easy. But, for the poor browser whose javascript is disabled, you might want to consider an alternative of server side.

Lets assume this simple scenario. You have list of completed and pending code statues. and Assume this list is longer and the completed list can appear in any place on the list but it is assured that all the completed lists would be all together.

So, all you want to do is to create an anchor to the very first of the completed list on the fly. Here is the snippet for that:

<!--
   __ __ _______
  | |/ /|    | |
  |   / | / | |
  | | | -- | |___
  |_| __||_|____| 

    Kaleb Woldearegay<contactkaleb@gmail.com>
 -->
<html>
<head><title>Simple </head>
<body>
<div id="completed"></div>
<table>
<tr>
    <td>1</td><td>code for module one</td>
</tr>
<tr>
    <td>2</td><td>code for module two</td>
</tr>
<tr class='completed'>
    <td>3</td><td>code for module 3</td>
</tr>
<tr class='completed'>
    <td>4</td><td>code for module 4</td>
</tr>
<tr class='completed'>
    <td>5</td><td>code for module 5</td>
</tr>
</table>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
        $(document).ready(function(){
                //perform only if there is atleast one completed row
                if ($("table tr.complete").length > 0){
            $("#completed").html("<a href='#anchored'>Go to Anchored</a>"); 
                        var completed = $("tr.complete:first").find("td:nth-child(2)");    //choose the second td
                        completed.html("<a name='anchored'>" + completed.html() + "</a>");//create the anchor
                        $("table tr.complete").css('background', 'green'); //colorize
        }  
                $("table tr.pending").css('background', '#cccFFF');
        });

</script>
</body>
</html>

See how you would solve these known algorithm problems

Check if there are three numbers a, b, c giving a total T from array A

Java solution for checking anagram strings – tell if phrases are anagrams

Kadane’s algorithm in C – Dynamic Programming

Check if two strings are anagrams or not

Implementing tokenizer and adding tokens to the linked list

Find K Complementary numbers from array Java implementation

binary tree problems with solution

testing k complementary pairs algorithm with junit

String Ordered Permutation Algorithm Problem

Find longest palindrom from sequence of characters

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*