Reputation: 251
I need to have a function that puts the code inside it in an HTML "a" element. I have tried many different variations of the code posted below and none of them have worked.
var doc = document.body;
function h1(text) {
var h1 = document.createElement("h1");
var t = document.createTextNode(text);
h1.appendChild(t);
doc.appendChild(h1);
}
function a(a, b) {
var doc1 = document.createElement("a");
doc.a;
var s;
s = document.createElement('script');
s.innerHTML = b;
doc.appendChild(doc1);
doc = doc1;
doc1.appendChild(s);
doc = document.body;
}
a("href=www.google.com", "h1(\"hello\");");
Upvotes: 1
Views: 80
Reputation: 251
Thank you @JLRishe your answer really helped me figure this one out. After, reviewing you code, editing mine, and digging through the internet for solutions I can up with this.
function h1(text) {
base = document.createElement("h1");
var t = document.createTextNode(text);
base.appendChild(t);
doc.appendChild(base);
}
function a() {
doc1 = document.createElement("a");
doc.appendChild(doc1);
doc1.appendChild(base);
}
function href(a) {
doc1.href = a;
}
a(h1("hello"));
href("www.google.com");
h1("hello");
It doesn't work for me in JSFiddle, but it works where I need it to.
Upvotes: 0
Reputation: 101728
I'm curious how you arrived at that particular attempt, but here is how you could do this correctly (at least this is what I think you're trying to do):
var doc = document.body;
function h1(text) {
var h1 = document.createElement("h1");
var t = document.createTextNode(text);
h1.appendChild(t);
return h1;
}
function a(a, b) {
var link = document.createElement("a");
link.href = a;
link.appendChild(b);
return link;
}
doc.appendChild(a("http://www.google.com", h1("hello")));
doc.appendChild(h1("wazzap"));
In general, I would recommend against having functions whose parameters or variables have the same name as themselves. That makes it very confusing.
Upvotes: 1