Reputation: 1
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>
Upvotes: 0
Views: 123
Reputation: 3224
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>
Upvotes: 0
Reputation: 479
You can do it like this: HTML:
<a id="link" href="#">Click me</a>
JavaScript:
document.getElementById("link").setAttribute("href", "page.html");
Upvotes: 2