0

How to get the child number ?

check screenshot

so when i click on the X button, that element will be removed, but it's only for item n2, so i need to get the number of the child when i click on it

<div class="col-xs-4">
       <a class="postimgsd" onclick="if(confirm('Are you sure, want to delete this image?')){delImage(2572);}else{} ">
        <span class="close">X</span> <img src="site/32000/2572/51c1e0a5f8715e33e74e58798cdc0f4d.jpg"></a></div>

i tired

    var child = document.getElementsByClassName('col-xs-4');
    var parent = child.parentNode;
    var index = Array.prototype.indexOf.call(parent.children, child);

but i got

Uncaught TypeError: Cannot read property 'children' of undefined at :3:53

How can i do that ?

JDEV
  • 69
  • 8
  • 1
    How is this duplicated ? maybe there's someone asked the same question but it's not the one mentioned – JDEV Dec 06 '19 at 19:14
  • i asked about how to got that number not how to fix that problem, i mean different code maybe – JDEV Dec 06 '19 at 19:15
  • In my opinion they close questions way too easily. Anyway. I updated my answer, let me know if it worked. – JMRC Dec 06 '19 at 19:31

1 Answers1

-1

getElementsByClassName returns an array, so when you use parentNode, you get undefined and you're trying to get the property children of an undefined variable.

What you can do is give each image a unique ID like id="image_123" and store this ID in the corresponding close button with a data-{name} attribute like data-gallery-image-id="image_123". When the button's click event is triggered, use the event.target.getAttribute('data-gallery-image-id') to get the ID of the image. Now you can use document.getElementById() to get the image you'd like to remove.

JMRC
  • 1,336
  • 16
  • 34