0

I'm trying to create an element onclick and hide the element when it is clicked but it does nothing?

Why does the hide() function do nothing?

<script type="text/javascript">
function show(){
  var a = document.getElementById('foo');
  var b = document.createElement("div");
  b.setAttribute('id', 'bar');
  b.setAttribute('onclick', 'hide()');
    a.appendChild(b);
b.innerHTML = 'TEXT CONTENT';
b.onclick = function() { 
    hide();
};
} 

function hide() {
    var x = document.getElementById('foo'); 
  var z = document.getElementById('bar');
  x.removeChild(z);
}
</script>

<div id="foo" onclick="show()">CLICK ME</div>
Aaron
  • 11,239
  • 18
  • 58
  • 73

3 Answers3

1

Add b.onclick = function() {hide();};

1

If this is occurring under IE, then see Stackoverflow - Why does an onclick property set with setAttribute fail to work in IE?

Community
  • 1
  • 1
typo.pl
  • 8,812
  • 2
  • 28
  • 29
1

you can use jquery method to register function it will work in both IE,FF

A sample for u

$(b).click(function() {
//call your function like hide() i have made a separate function for cleaner code and re usability 
        });

function hide()
{

}
ankur
  • 4,565
  • 14
  • 64
  • 100