Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and remove div from body in javascript

I'm kinda new to javascript, and probably there are other people who already asked similar question, but I hope you can help me anyway. I'm trying a simple basic operation of add/remove of a div. The add works fine, the remove is never called.

function $(el) {
    return document.getElementById(el);
}

function remove() {
    console.log("remove called");
    var child = $('second');
}

function addContainer() {
    console.log("addContainer called");
    var aContainer = document.createElement('div');
    aContainer.setAttribute('id', 'second');
    aContainer.innerHTML = "<a href=\"#\" onclick=\"remove()\">second</a>";
    document.body.appendChild(aContainer);
}

In the addContainer I try to add the onclick function callback, but apparently it doesn't work.

Here the jsfiddle of reference http://jsfiddle.net/m8kyav2b/

DO you know why 1- the remove function is never called? 2- once I click on the remove link, the innerHTML is removed, but not the div "second"?

Thanks a lot in advance

like image 679
CKY Avatar asked May 06 '26 07:05

CKY


2 Answers

Try it like this, it will work:

DEMO

function $(el) {
    return document.getElementById(el);
}

function removeit() {
    alert("remove called");
    var child = $('second');
    child.remove();


}

function addContainer() {
    console.log("addContainer called");
    var aContainer = document.createElement('div');
    aContainer.setAttribute('id', 'second');
    aContainer.innerHTML = "<a href=\"#\" onclick=\"removeit()\">second</a>";
    document.body.appendChild(aContainer);
}

SIDENOTE:

Calling remove() as your function won't work as it is a native javascript function. You didn't actually remove the div in your function, too!

like image 167
baao Avatar answered May 09 '26 01:05

baao


Here is a helpful link: Remove element by id. The below code is tested and works (it will upon mouse over delete the HTML tag, so basically just change the syntax around a little to have it delete what ever tag you want.

<p id="el" onmouseover="remove()">test</p> <!--we are deleting with JavaScript this HTML <p> tag. -->

function remove() {
  var element = document.getElementById("el"); /* finding and assigning element to variable element */
  document  
  element.parentNode.removeChild(el); // then deleting the parent and child (please refer to link)
}

as far as the rest of your question. Look here: add onclick event to newly added element in javascript.

like image 28
Kris Avatar answered May 09 '26 01:05

Kris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!