Why does my button need to be clicked twice for the onclick event to trigger? There're some other thread on stackoverflow with the same problem, but in all the thread i found, the original poster puts the event handler inside the function. It's not like that with my code.
Html
<body>
<ul id="parentList">
<li>First child</li>
<li>Second child</li>
<li>Third child</li>
<li>Forth child</li>
<li>Fifth child</li>
</ul>
<button type="button" id="delete">Delete first child</button>
</body>
Script:
var parentList = document.getElementById("parentList");
document.getElementById("delete").onclick = function() {
parentList.removeChild(parentList.firstChild);
};
Demonstration: onclick-error
Please Sign up or sign in to vote. the button from asp.net once pressed could eventually trigger twice action because at the HTML Interface there's a javascript ONCLICK properties. Now it's just run once, nor twice.
How to Use the onclick event in JavaScript The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.
It would be good to re-open this as an issue that still needs to be fixed, encouraging others to step in and offer a PR. I feel that if you add an onClick function to a component, then it should be called when that component is clicked, consistently in all browsers.
There is nothing wrong with your click handler on the button. The problem is with the way you are removing the first child. If you add this small change to your function: You will notice that the first click logs out some empty spaces with a line break.
The first "element" within the parentList is whitespace. You can see this by console logging the element within the event listener.
You therefore need to only filter out the li
elements within the parent item.
document.getElementById("delete").onclick = function() {
var listItems = document.querySelectorAll("#parentList > li");
if (listItems.length > 0) {
listItems[0].remove();
}
};
https://jsfiddle.net/ofLvac32/13/
You could also use parentList.firstElementChild
instead of parentList.firstChild
, which filters out any invalid nodes (whitespace).
An example of this
var parentList = document.getElementById("parentList");
document.getElementById("delete").onclick = function() {
parentList.removeChild(parentList.firstElementChild);
};
https://jsfiddle.net/ofLvac32/37/
With elementChild
, you look for any child, including white spaces.
You could use parentList.firstElementChild
instead to get the first child element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With