views:

1041

answers:

2

Hi everyone, I have a livesearch script that i need to populate my html menu with information.

i have a menu how looks something like this:

<a href="?page=page&id=">Menu item</a>

what i'm looking for is a piece of code that would do this to the link:

<a href="?page=page&id=1">Menu item</a>

i have a Javascript that pulls out value ID from a database table (livesearch), now i only need it to get into the href on the fly.

Any suggestions?

+4  A: 
<a href="?page=page&id=" id="link1">Menu item</a>

<script type='text/javascript'>
var myidtoinsert = 5;
document.getElementById("link1").href += myidtoinsert;
</script>

Give your a tag an id and then just use document.getElementById to get at the href attribute.

ChristopheD
Perfect ChristopheD, just what i was looking for. Thanks a bunch!
Filip Palm
The downside with thisone was that i need one id="link+" for every href.
Filip Palm
You need to give the element a unique identifier as to be able to manipulate it DOM-wise in Javascript. The only javascript alternative I can think of for the moment would be 'getting -all- the a tags' on a page and iterating over them for automatically adding href tags. Is there a reason you can't generate the a tag id @ the server-side?
ChristopheD
+1  A: 
function addPageIds(){

    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++){
        if (/id=$/.test(links[i].href)) links[i].href += "1";
    }

}
MiffTheFox
MiffTheFox, this worked great. There is a typo in link[i].href (links[i].href).Thanks a bunch!
Filip Palm