How to replace an element with a completely different?

29 views
Skip to first unread message

Ben Stover

unread,
Mar 28, 2016, 4:52:51 AM3/28/16
to Greasemonkey Users
Assume I have the following code:

<div class"foobar">
....
<a class="aaa" .....> .... </a>
....
</div>

Now I want to completely replace the <a> element (including child stuff) by another.
Then the follawing does not work:

var address = document.URL;
var div = document.getElementsByClassName("foobar.aaa")[0];
div = "<a href=\"" + address + "\">" + address + "</a>";

How else does that work?

Ben









Tithen Firion

unread,
Mar 31, 2016, 8:50:08 AM3/31/16
to greasemonkey-users
If you want to replace only <a> element and leave everything else in <div> as is, you need to find that <a> element first:
var aOld = document.querySelector("div.foobar a.aaa"); // returns first match
Then you need to create new <a> element:
var aNew = document.createElement("a");
aNew
.href = address;
aNew
.innerHTML = address; // content of <a> element
And last thing to do is to replace this element with the old one:
aOld.parentNode.replaceChild(aNew, aOld);
Reply all
Reply to author
Forward
0 new messages