1

I have a button that, when clicked, calls a function show().

This function dynamically creates a DIV with a close button!

This close button should call a function to remove the created DIV from the DOM.

Considering that this second function will only be necessary within this scenario, can I do that without having to declare the function explicitly?

Here's a demo:

More clearly, the idea is to dispense the need to declare the "close ()" function and set this functionality within the "show ()" function using only vanilla JS.

function show() {
	var div = document.createElement('div');
  div.setAttribute("id", "myDiv");
  div.innerHTML = "Hello World ";
  var button = document.createElement('button');
  button.innerHTML = "CLOSE";
  button.setAttribute("onclick","close();");
  div.appendChild(button);
  document.body.appendChild(div);
}

function close() {
  //code to remove element
}
#myDiv {
  background:yellow;
  border:1px solid black;
  margin-top:10px;
  padding:20px;
}
<button onclick="show();">
  Show
</button>

JSFIDDLE: https://jsfiddle.net/do4yq2w9/1/

1 Answer 1

1

You can assign onclick of the button with a new function like below:

function show() {
	var div = document.createElement('div');
  div.setAttribute("id", "myDiv");
  div.innerHTML = "Hello World ";
  var button = document.createElement('button');
  button.innerHTML = "CLOSE";
  button.onclick = function() {
  	document.getElementById('myDiv').remove();
  }
  div.appendChild(button);
  document.body.appendChild(div);
}
#myDiv {
  background:yellow;
  border:1px solid black;
  margin-top:10px;
  padding:20px;
}
<button onclick="show();">
  Show
</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.