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.
2 Answers
Reset to default 2You could find all p
s 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>`;
});