最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to find each occurrence of a "<P>" within html and replace it - Stack Overflow

programmeradmin2浏览0评论

Hope you can help.

I would like to be able to take the following html example:

<p>This is some text.</p>

<p>This is some more text.</p>

and use a javascript function (not jquery) to find each unique occurrence of </p> and replace it so it becomes (for example)...

<p>This is some text. <span>Random text from function.</span></p>

<p>This is some more text. <span>Different random text from function.</span></p>`

To insert a random quote of the day or suchlike. This must be within the <p></p> tags.

Hope you can help.

I would like to be able to take the following html example:

<p>This is some text.</p>

<p>This is some more text.</p>

and use a javascript function (not jquery) to find each unique occurrence of </p> and replace it so it becomes (for example)...

<p>This is some text. <span>Random text from function.</span></p>

<p>This is some more text. <span>Different random text from function.</span></p>`

To insert a random quote of the day or suchlike. This must be within the <p></p> tags.

Share Improve this question asked Mar 6 at 11:53 TJS101TJS101 4921 gold badge8 silver badges19 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 2

You could find all ps with document.querySelectorAll, iterate them with forEach and add a span element. Remember to pick random quotes such way so they don't repeat:

const quotes = ['Random text from function.', 'Different random text from function.'];

function replaceQuotes(){
  
  const source = quotes.slice(); // make a copy to destroy
  
  document.querySelectorAll('p').forEach(el => {
    
    const quote = source.splice(Math.random() * source.length | 0, 1); // pick a random quote and remove from it from the source
    const span = document.createElement('span');
    span.textContent = quote;
    el.append(span);
  });
}
<p>This is some text.</p>
<p>This is some more text.</p>
<button onclick="replaceQuotes()">Append</button>

in below code, you get all P tags in paragraphs variable using document.querySelectorAll(). Than we need to use for loop to insert a some data or text in each p tag.

const paragraphs = document.querySelectorAll("p");

    paragraphs.forEach(p => {
        const randomText = quotes[Math.floor(Math.random() * quotes.length)];
        p.innerHTML += ` <span>Random text from function.</span>`;
    });

发布评论

评论列表(0)

  1. 暂无评论