Reputation: 3
I want to change my dynamically created div but i can't get this working it's keep creating new divs
var div = document.getElementById('windowx');
var btn;
var doc = content.document
if (div)
{
div = document.getElementById('windowx')
div.innerHTML = "something new"
}
else
{
doc = content.document
div = doc.body.appendChild(doc.createElement("div"))
div.setAttribute("id", "windowx")
div.setAttribute("style",
"position: fixed; top: 100px; left: 100px; width: 20em;"
+ "border: 2px outset orange; background-color: cornsilk;"
)
btn = div.appendChild(doc.createElement("button"))
btn.setAttribute("style", "position: absolute; bottom: 1ex; right: 1ex;")
btn.setAttribute("onclick", "document.body.removeChild(this.parentNode)")
btn.appendChild(doc.createTextNode("Zamknij"))
}
Upvotes: 0
Views: 476
Reputation: 816580
Now that it is clear that it is for a Firefox plugin:
document.getElementById
will search for that element in the browser UI, not the web page. But later you are adding the element to the page. Therefore you have to search in the page for that element:
var div = content.document.getElementById('windowx');
Also, you are making some unnecessary method calls. Here is a cleaner version of your code:
var doc = content.document,
div = doc.getElementById('windowx'),
btn;
if (div) {
div.innerHTML = "something new"
}
else {
div = doc.body.appendChild(doc.createElement("div"))
div.setAttribute("id", "windowx")
div.setAttribute("style",
"position: fixed; top: 100px; left: 100px; width: 20em;"
+ "border: 2px outset orange; background-color: cornsilk;"
)
btn = div.appendChild(doc.createElement("button"))
btn.setAttribute("style", "position: absolute; bottom: 1ex; right: 1ex;")
btn.setAttribute("onclick", "document.body.removeChild(this.parentNode)")
btn.appendChild(doc.createTextNode("Zamknij"))
}
Upvotes: 2
Reputation: 532505
For me it was choking on content.document
, the window object doesn't have a content property so I'm not sure what you were referencing. Cleaned up a bit and it seems to work. Note I'm adding the click handler directly instead of setting it as an attribute. See here where I have it triggered by a jQuery button click handler: http://jsfiddle.net/hN8uz/1/
var doc = document;
var div = doc.getElementById('windowx');
var btn;
if (div) {
div.innerHTML = "something new";
}
else {
div = doc.body.appendChild(doc.createElement("div"));
div.setAttribute("id", "windowx");
div.setAttribute("style", "position: fixed; top: 100px; left: 100px; width: 20em;" + "border: 2px outset orange; background-color: cornsilk;");
btn = div.appendChild(doc.createElement("button"));
btn.setAttribute("style", "position: absolute; bottom: 1ex; right: 1ex;");
btn.onclick = function() {
document.body.removeChild(this.parentNode);
};
btn.appendChild(doc.createTextNode("Zamknij"));
}
Upvotes: 0