0

I'm trying to replace the value of an html element's attribute with javascript. I'm pretty sure I've seen it done before, but I'm not sure how the syntax works on such things. Example:

<a href="javascript:bookmarksite('Website Name', "<script type="text/javascript">document.write(location.href);
</script>')">Click Here to Bookmark this Page</a>
1
  • This might be helpful: setAttribute. Commented Mar 21, 2013 at 17:32

2 Answers 2

2

You can do it like this: HTML:

<a id="link" href="#">Click me</a>

JavaScript:

document.getElementById("link").setAttribute("href", "page.html");
Sign up to request clarification or add additional context in comments.

1 Comment

This changes only a property of the element, OP wants to change the value of an attribute : (.
0

Unobtrusive JavaScript is always a nice way to handle these kinds of things:

(function(d){
    var modern = function(){
        return(d.addEventListener);
    }, event = function(obj, evt, fn){
        if(modern()) {
            obj.addEventListener(evt, fn, false);
        } else {
            obj.attachEvent("on" + evt, fn);
        }
    }, load = function(fn){
        if(modern()) {
            d.addEventListener("DOMContentLoaded", function go(){
                d.removeEventListener("DOMContentLoaded", go, false);
                fn();
            }, false);
        } else {
            d.attachEvent("onreadystatechange", function go(){
                if(d.readyState === "complete") {
                    d.detachEvent("onreadystatechange", build);
                    fn();
                }
            });
        }
    }, init = function(){
        var link = d.getElementById("bookmark_link");
        event(link, "click", function(e){
            bookmarksite("Website Name", location.href);
            // Set attribute(s) here
            link.setAttribute("href", "whatever_you_want.html");
        });
    };
    load(init);
})(document);

Then the in the link:

<a href="#" id="bookmark_link">Bookmark this page</a>

1 Comment

Thanks everyone! I ended up using php instead. <a href="javascript:bookmarksite('Site Name', 'http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];?>')" title="Bookmark Name of Website">Click here to Bookmark!</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.