0

I have a textbox. On focus I call a javascript function in which I create a new element with this way:

var label = document.createElement("label");
label.innerHTML = "*For a more secure password use letters and digits";
document.getElementById('picturediv').appendChild(label);

But onblur I call another function and then I want to remove this element. I've tried with the remove but it is not working. I am not sure if the remove is suitable for that.

4

1 回答 1

2

You can remove it this way:

function removeLabel() {
    document.getElementById('picturediv').removeChild(document.getElementById('picturediv').getElementsByTagName('label')[document.getElementById('picturediv').getElementsByTagName('label').length - 1]);
}

edit:

The function with comments:

function removeLabel() {
    var parentNode = document.getElementById('picturediv'); // The parentNode of the label element

    var tagsWithLabel = parentNode.getElementsByTagName('label'); // All elements with tag name label

    var length = tagsWithLabel.length; // The length of the node array

    parentNode.removeChild(tagsWithLabel[length - 1]); // Deleting the last element with tage name label from parentNode.
}

edit because of comment:

function removeLabel(id) {
    document.getElementById(id).removeChild(document.getElementById(id).getElementsByTagName('label')[document.getElementById(id).getElementsByTagName('label').length - 1]);
}

to delete label 1: removeLabel('picturediv'); to delete label 2: removeLabel('picturediv2');

于 2012-04-28T09:40:17.457 回答