0

Hello

So, I have some JS code that creates HTML elements dynamically. More precisely, it creates div elements that also have some other things inside them.

Each of these div elements has an img element inside them. How can I achieve such effect, that when the img element is clicked in a certain div element, that exact div element is deleted?

This is my code which creates elements dynamically:

function addQuestion(question){
    var s = "<div style=\"width:100%;background-color:transparent;border-top:none;border-bottom:2px solid white;border-right:none;border-left:none;\"><div style=\"margin:5px;font-family:Verdana;color:white;\">"+"<p>"+noTag(question)+"</p>"+"</div></div>";

    var div = document.createElement('div');
    div.innerHTML = s;
    document.getElementById("div_questions").appendChild(div);
}

Currently it does not create the img element. But the idea is that in each of these div elements it also creates an img element which, when clicked, deletes that and only that div element.

How can I achieve this?

Tee-Tree
  • 31
  • 5

1 Answers1

0

try following code....

            var _cotainerDiv = document.getElementsById("holderDiv");

            var _tempDiv = document.createElement("div");
            $(_tempDiv).css({
                //Css properties...
            });

            _cotainerDiv.appendChild(_tempDiv);

            var _tempImg = new Image();
            _tempImg.src = "...../imagePath";
            _tempImg.onload=function(){
                this.addEventListener("click", onImageClick);
            }
            _tempDiv.appendChild(_tempImg);


            function onImageClick(event)
            {
                var _curImg = event.target;

                _cotainerDiv.removeChild(_curImg.parentElement);
            }
spankajd
  • 934
  • 7
  • 13