Rod
Rod

Reputation: 15457

Remove child element but keep its content

What's the best way to remove the strong element during the onclick event?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
</head>
<body>
    <span onclick="testfx();"><strong>Test without styles</strong></span>
</body>
</html>
<script type="text/javascript">
    function testfx() { alert('test'); }
</script>

Upvotes: 0

Views: 467

Answers (2)

Caprica Six
Caprica Six

Reputation: 1500

Well, here it is: http://tinker.io/1f282/1

el.addEventListener('click', function () {
    var toRemove = this.getElementsByTagName('strong')[0];

    if (!toRemove) {
        return;
    }

    while (toRemove.firstChild) {
        el.appendChild(toRemove.firstChild);
    }
});

(where el is your span). Note one very important thing: You should not mix javascript in your html. It's bad in all kinds of ways, you can just google "separation of concerns" and "unobtrusive javascript" to see why.

Upvotes: 15

painotpi
painotpi

Reputation: 6996

You should be handling (javascript) events in a script file and not in the HTML. It will help you with,

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

You could try this,

var x = document.getElementById("test");
var y = document.getElementById("testChild");
x.addEventListener('click', function () {
    this.removeChild(y);
});

Test Link

EDIT

If you just want to remove the "strong" effect do this,

var x = document.getElementById("test");
var y = document.getElementById("testChild").innerHTML;
x.addEventListener('click', function () {
    this.innerHTML = y;
});

Test Link

Upvotes: 1

Related Questions