如何在按钮间添加换行?JavaScript实现br标签在按钮外的方法
Got it, let's sort this out! The problem with your original JavaScript was that it was inserting the <br> element inside the first button (as a child element) instead of placing it between the two buttons as a sibling. Here's how to correctly add the line break outside the buttons:
Method 1: Insert after the first button
This approach targets the first button and adds the line break immediately after it:
// Grab the first button element const buttonOne = document.getElementById('buttonOne'); // Create a new line break element const lineBreak = document.createElement('br'); // Insert the line break as a sibling AFTER buttonOne buttonOne.insertAdjacentElement('afterend', lineBreak);
Method 2: Insert before the second button
Alternatively, you can target the second button and insert the line break right before it:
// Grab the second button element const buttonTwo = document.getElementById('buttonTwo'); // Create a new line break element const lineBreak = document.createElement('br'); // Insert the line break just before buttonTwo (as a sibling) buttonTwo.parentNode.insertBefore(lineBreak, buttonTwo);
Why this works
Both methods ensure the <br> is placed outside the button elements. If you were using something like buttonOne.appendChild(lineBreak) before, that's why the line break ended up inside the button—appendChild adds elements as children, not siblings.
After running either of these scripts, your HTML structure will look like this (which gives the proper line break between buttons):
<button id="buttonOne"> click one me </button> <br> <button id="buttonTwo"> click on me too </button>
内容的提问来源于stack exchange,提问作者Deke

