0

I have this below span div and I copy this to another place in the DOM. But the onclick function I need to remove and place another onclick function.

<span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>

Here I have to remove the onclick="expand_collapseChildnodes('childNode1')" for the copied element and replace it with onclick="checkNodes('childNode1')".

2
  • Your question isn't really clear enough. What do you mean by 'remove and replace'? Can't you simply edit the markup? Commented Aug 20, 2013 at 9:16
  • The requirement is not clear. Provide more details. Commented Aug 20, 2013 at 9:18

3 Answers 3

3

Consider a sample HTML page:

<html>
    <head>
    </head>
    <body>
        <div id ="d1">
        <span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>
        </div>
        <div id ="d2">
        </div>
    </body>
</html>

Now to move the element with id abc from DOM element with id d1 to another with id d2

//get the element
var element = document.getElementById("abc");

//detach from source
document.getElementById("d1").removeChild(element);

//remove onclick attribute
element.removeAttribute("onclick");

//add the modified attribute
element.setAttribute("onclick", "sampleFunc()");

//attach the element to another source
document.getElementById("d2").appenChild(element);
Sign up to request clarification or add additional context in comments.

1 Comment

@abhinna11 How do i get parameter of previous function then?
1

http://jsfiddle.net/KvnKZ/1/

var div=document.getElementsByTagName("div");
var span=document.getElementById("abc");
var newSpan=span.cloneNode(true);
newSpan.setAttribute("id","newID"); //change id
newSpan.setAttribute("onclick","myFunc()"); //change onclick event handler

div[0].appendChild(newSpan);

Comments

0
document.getElementById("abc").onclick = function (){checkNodes('childNode1');}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.