Save

How to remove the next element using JavaScript (without using jQuery)

I need something like this.

<a onclick="SaveNote(this);" >Save</a> <a href="javascript:void(0);" id="112">Cancel</a> <a href="javascript:void(0);" id="112">Delete</a> 

If I click on the Save binding, I want to remove all three binding elements, as shown above, without using id and replace them with the Edit anchor. I currently have Javascript code that looks something like this:

 function SaveNote(e){ e.nextSibling.removeNode; e.nextSibling.removeNode; e.nextSibling.removeNode; } 

Do you have any ideas on this issue?

+4
source share
4 answers

You can do something like this

HTML

 <div>Stuff before</div> <div> <a id="save" href="#">Save</a> <a id="cancel" href="#">Cancel</a> <a id="delete" href="#">Delete</a> </div> <div>Stuff after</div> 

Javascript

 function emptyNode(node) { while (node.firstChild) { node.removeChild(node.firstChild); } } function saveNote(e) { var parent = e.target.parentNode, edit = document.createElement("a"); emptyNode(parent); edit.id = "edit"; edit.href = "#"; edit.appendChild(document.createTextNode("Edit")); parent.appendChild(edit); } document.getElementById("save").addEventListener("click", saveNote, false); 

Jsfiddle on

Note: this requires addEventListener support, which is easy to handle.

+1
source

removeNode seems non-standard. Try the following:

 if(e && e.nextSibling) { e.parentNode.removeChild(e.nextSibling) } 
+10
source

Instead of reomveNode try removeNode(); .

+2
source

I wanted to do the same thing as this question, but without referring to the parent node. After some searches, this is what I found!

It seems that there is actually a function that will allow you to do this without reference to the parent node; it is called remove(); .

Here is a demo.

 function removeNextNode(elem) { elem.nextElementSibling.remove(); } 
 a { display: block; } 
 <a onclick="removeNextNode(this);" href="#">Click to remove the next node...</a> <a href="#">another node</a> <a href="#">another node</a> <a href="#">another node</a> <a href="#">another node</a> <a href="#">another node</a> <a href="#">another node</a> 

Please write a comment if this answer can be improved.

+2
source

Source: https://habr.com/ru/post/1488476/


All Articles