function greet () {
console.log ("Hi there!");
}
function addButton () {
document.createElement("[wanted_HTML_tag_here]");
}
There is separate HTML document. It has a button that calls the function addButton() upon being pressed. Said function has to create a new element and append it to the element. Pressing this new button has to call the function greet().
I try with [element_name].setAttribute("[attribute]", "[attribute_value]") but useless Also trying document.[element_to_append_into].appendChild([element_being_added]); but same
Here's a complete working example (it is one way of doing it):
<html lang="en">
<body>
<button id="btn">Create Button</button>
</body>
<script>
function greet() {
console.log('Hi there')
}
function addButton() {
const button = document.createElement('button')
const buttonTextNode = document.createTextNode('Click')
button.appendChild(buttonTextNode)
button.onclick = greet
document.body.appendChild(button)
}
// get the button that creates other buttons
const buttonCreator = document.getElementById('btn')
buttonCreator.onclick = addButton
</script>
</html>
Is it possible to merge the
const buttonCreator = document.getElementById('btn')
buttonCreator.onclick = addButton
into
function addButton() {
const button = document.createElement('button')
const buttonTextNode = document.createTextNode('Click')
button.appendChild(buttonTextNode)
button.onclick = greet
document.body.appendChild(button)
}
?????????????????????????
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.