Giedrius Giedrius - 4 months ago 13
HTML Question

Function gives an error "div id" is not defined.

I have a function which creates a new div with the output of the funtion toArabic.

function createListItem(value) {

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block' + i;
var classString = iDiv.className.toString();
document.getElementsByTagName('body')[0].appendChild(iDiv);
iDiv.innerHTML = toArabic(value).toString() + " " + "<span class='remove' onclick=' removeDummy(" + classString + "); '>x</span>";
i++;
}


It creates a div with Id block#, so the first one is block0, second is block1 and so on.

I want to add a button "remove" which on clicking the "x" would remove the created div. I was able to alert the div name in removeDummy function, but it still gives an error "block0 is nod defined".

Remove function:

function removeDummy(value) {

var elem = document.getElementById(value);
elem.parentNode.removeChild(elem);
return false;

}


The function worked until i gave it the value, but it would delete the oldest div so i decided to give it a div id to delete exactly the one that is cliked on.

What could cause this error ? Why would the function work with alert, but not with remove ?

How could I solve this problem ?

Thanks in advance!

Answer

Couple little errors:

First: Every div you create has the same id but different classNames. This should be reversed. Think of id's as your personal id's, and class names as jobs. Two people can't have the same id but they can have the same job.

iDiv.id = 'block' + i;
iDiv.className = 'block';

Second: Currently your remove buttons look like this:

<span class='remove' onclick=' removeDummy(block1); '>x</span>

If you click on it, then it tries to call removeDummy and pass it the variable block1. If you didn't defined block1 before, then it will contain the element with the same idea. You need to encapsulate this value in '-s

"<span class='remove' onclick=' removeDummy('block" + i + "'); '>x</span>"