You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在按钮间添加换行?JavaScript实现br标签在按钮外的方法

Fixing the Line Break Placement Between Buttons

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:17:10