Question

I've used a for loop to create a bunch of images with unique ids. They look something like this:

<img src="image.jpg" id="110021002" />
<img src="image.jpg" id="110021003" />
<img src="image.jpg" id="110031002" />
...

Later on in the code I want to select one of the images by ID and remove it. I tried the following:

var removeId = '110021002';
var img = document.getElementById(removeId);
img.parentNode.removeChild(img);

But I get the following error:

Cannot read property 'parentNode' of null

Not quite sure what's going on here. Is it because the images were created dynamically?

Was it helpful?

Solution

Your code works perfect: http://jsbin.com/zexoweyu/3/edit for the first time you remove an element, obvisouly on the second attempt the element is not there and it will throw the given error.

On the fiddle:

  • Click once, works
  • Click again, fails because the element with that ID is no longer there.

And yes, ids can start with numbers.

**Attribute ID** Specifies a unique id for the element. Naming rules:
Must contain at least one character
Must not contain any space characters
In HTML, all values are case-insensitive

OTHER TIPS

You can't have IDs that start with a number. Try prefixing them with a letter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top