tags:

views:

1572

answers:

2

for an element in DOM,such as an "A" element,how to replace it with a "span" instead?

+6  A: 

by using replaceChild():

<html>
<head>
</head>
<body>
  <div>
    <a id="myAnchor" href="http://www.stackoverflow"&gt;StackOveflow&lt;/a&gt;
  </div>
<script type="text/JavaScript">
  var myAnchor = document.getElementById("myAnchor");
  var mySpan = document.createElement("span");
  mySpan.innerHTML = "replaced anchor!";
  myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
apphacker
this example wouldn't work. You should put the script block at the end of the body to make it work. Furthermore, just for fun: try adding the line [alert(myAnchor.innerHTML)] after the operation.
KooiInc
Ah yeah, good point.
apphacker
Hahahahahaha. I just did the alert. You sir, are awesome.
apphacker
Theres a spelling mistake with StackOverflow in the anchor innerText
rahul
+1  A: 
var a = A.parentNode.replaceChild(document.createElement("span"), A);

a is the replaced A element.

Kamarey