简体   繁体   中英

Removing a newly created element in JavaScript with creating a button

I have added a <p> to a <div> by this code and made a button, too.

var selectedId = this.value;
var divElem = $("#selectedItem");

var bElem = document.createElement("Button");
var bElemInnerHTML = document.createTextNode("Erase");
bElem.addEventListener('click', function () {
    remove(this.value);
}, true);
bElem.appendChild(bElemInnerHTML);

var pElem = document.createElement("p");
var pElemInnerHTML = document.createTextNode(this.value);
pElem.setAttribute('id', selectedId);
alert(pElem.getAttribute('id'));
pElem.style.fontSize = '25px';
pElem.style.textAlign = 'center';
pElem.style.margin = '5px';
pElem.appendChild(pElemInnerHTML);
pElem.appendChild(bElem);

divElem.append(pElem);

I add to the button to run the remove function when clicked on

function remove(id){
var emad = document.getElementById(id);
emad.parentNode.removeChild(emad);}'

but it doesn't work.

bElem.addEventListener('click', function () {
    remove(this.value);
}, true);

this.value in the above context refers to the Button element's value property(which is a string), not the ID of the Button. Also, you haven't defined the ID, so this.id would return "" (an empty string)

bElem.addEventListener('click', function () {
    remove(this.id);
}, true);

You can modify remove() to accept an Object instead:

function remove(btn){
    emad.parentNode.removeChild(btn);
}

bElem.addEventListener('click', function () {
    remove(this);
}, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM