Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript add ID to HTML href

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?

like image 927
Filip Palm Avatar asked Sep 13 '09 08:09

Filip Palm


2 Answers

<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.

like image 69
ChristopheD Avatar answered Nov 09 '22 21:11

ChristopheD


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";
    }

}
like image 26
MiffTheFox Avatar answered Nov 09 '22 20:11

MiffTheFox