[英]How to add hr after each p? using the loop for
document.querySelectorAll('p').forEach((elem) => {
elem.insertAdjacentHTML('afterend', '<hr/>');
});
<article>
<h3>What is Lorem Ipsum?</h3>
<p>First</p>
<h3>Where does it come from?</h3>
<p>Second</p>
<h3>Why do we use it?</h3>
<p>Third</p>
It is not possible to modify the specified markup无法修改指定的标记
document.addEventListener("DOMContentLoaded", function(){ var element = document.querySelectorAll('p'); for (var i = 0; i < element.length; i++) { element[i].insertAdjacentHTML('afterend', '<hr/>'); } });
<?DOCTYPE html> <html> <head> <title>Test Page</title> </head> <body> <article> <h3>What is Lorem Ipsum?</h3> <p>First</p> <h3>Where does it come from?</h3> <p>Second</p> <h3>Why do we use it?</h3> <p>Third</p> </article> </body> </html>
Your solution seems to work just fine.您的解决方案似乎工作得很好。 Just be wary of using the getElementsByTagName as it will select ALL p tags on the page and not just the three you have in your example.
请小心使用 getElementsByTagName,因为它会 select 页面上的所有 p 标签,而不仅仅是您在示例中拥有的三个标签。
document.querySelectorAll('p').forEach((elem) => { elem.insertAdjacentHTML('afterend', '<hr/>'); });
<h3>What is Lorem Ipsum?</h3> <p>First</p> <h3>Where does it come from?</h3> <p>Second</p> <h3>Why do we use it?</h3> <p>Third</p>
const paragraphs = document.querySelectorAll('p'); for(let item of Array.from(paragraphs)) { const hr = document.createElement("hr"); item.appendChild(hr) }
<h3>What is Lorem Ipsum?</h3> <p>First</p> <h3>Where does it come from?</h3> <p>Second</p> <h3>Why do we use it?</h3> <p>Third</p>
before close article tag:) and then use 2 Way:在关闭文章标签之前:) 然后使用 2 方式:
use CSS (simple & best) Show sample in jsfiddel使用 CSS(简单和最佳)在 jsfiddel 中显示示例
or use array in javascript或在 javascript 中使用数组
Array.from(document.getElementsByTagName("p")).forEach(function(e, i) { e.append(document.createElement("hr")); });
<article> <h3>What is Lorem Ipsum?</h3> <p>First</p> <h3>Where does it come from?</h3> <p>Second</p> <h3>Why do we use it?</h3> <p>Third</p> </article>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.