views:

799

answers:

5

Hi

I have tried finding a simialr example and using that to answer my problem, but I can't seem to get it to work, so apologies if this sounds similar to other problems.

Basically, I am using Terminal Four's Site Manager CMS system to build my websites. This tool allows you to generate navigation elements to use through out your site.

I need to add a custom bit of JS to append to these links an anchor.

The links generated are similar to this:

<ul id="tab-menu">
<li><a href="/section/page">test link, can i rewrite and add an anchor!!!</a></li>
</ul>

I can edit the css properties of the link, but I can't figure out how to add an anchor.

The JQuery I am using is as follows:

<script type="text/javascript" src="http://jquery.com/src/jquery-latest.pack.js"&gt;&lt;/script&gt;
<script type="text/javascript">
    $(document).ready(function(){
    // everything goes here

    $("#tab-menu").children("li").each(function() { 
     $(this).children("a").css({color:"red"});

     });

    });
</script>

Thanks in advance for any help.

Paddy

+2  A: 

sort of duplicate of this: http://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery

just copy the old href and add anchor to it and paste that back

var link = $(this).children("a").attr("href");
$(this).children("a").attr("href", link+ "your own stuff");
Mafti
A: 

I can now target the html by using the following:

$(this).children("a").html("it works");

I assumed that:

$(this).children("a").href("something");

would edit the href but I am wrong.

Paddy

Use something like $(this).children("a").attr("href","something") and you're fine.
moff
+1  A: 

A nice jQuery-based method is to use the .get(index) method to access the raw DOM element within your each() function. This then gives you access to the JavaScript link object, which has a property called 'hash' that represents the anchor part of a url. So amending your code slightly:

<script type="text/javascript">
    $(document).ready(function(){
    // everything goes here

        $("#tab-menu").children("li").children("a").each(function() {   
            $(this).css({color:"red"}).get(0).hash = "boom";
        });

    });

Would change all the links in "#tab_menu li" to red, and attach "#boom" to the end.

Hope this helps!

jsidnell
Thanks, this works perfectly.Paddy
A: 

I am not sure for the answer, I dint try

$("#tab-menu").children("li").children("a").each(function() {   
              //  $(this).css({color:"red"}).get(0).hash = "boom";
            var temp_url = $(this).href +'#an_anchor';//or var temp_url = $(this).attr('href');
          $(this).attr('href', temp_url);
    });
P.M
A: 

$(document).ready(function(){ // everything goes here

    $("#tab-menu").children("li").children("a").each(function() {   
        $(this).css({color:"red"}).get(0).hash = "boom";
    });

});

in google chrome, this doesnt work!!!

Pavel