Something like this would be the easiest
let elements = document.querySelectorAll('p');
elements.forEach((el) => {
el.innerHTML = '<span>Added Span</span>';
});
Put that in a function that you call every time you add an element.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello :)
Thank you for looking into my question!
I must add elements to existing websites that I cannot control the HTML output of.
So, I can NOT force every <p> to have an ID, otherwise, I could simply store all IDs in an array, so that I can later tell, which <p> tag I have already processed (and which one not)
Long story short, here is what I must achieve:
I must add a <span> element to every existing <p> which exists upon loading the website
Additonally, I must also add a <span> to every NEWLY added <p> which gets added later dynamically
No <p> should get multiple new <span> "children". (so, I must know, which <p> tags already got a new <span> upon page load, and which did not)
Below is my code.
So far, I only managed to add a <span> to every existing <p> upon page load.
Also, I managed to dynamically add new <p> tags for testing purposes.
However, I neeed your guys' help to also add a <span> to every newly added <p>
Mind you, I am NOT the one creating the new <p> tags dynamically! The page itself does, and I don't know when it will happen!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
p
{
font-weight:bold;
font-size:20px;
min-height:20px;
}
</style>
</head>
<body>
<form>
<input type="button" id="add" value="Add a <p>">
</form>
<div id="container">
<p style="background-color:yellow;"></p>
<p style="background-color:green;"></p>
<p style="background-color:cyan;"></p>
</div>
<script>
window.addEventListener('load', function()
{
var all_p = document.querySelectorAll("p");
var all_span = [];
for(var i=0, current_p; current_p = all_p[i++];)
{
all_span[i] = document.createElement('span');
all_span[i].innerHTML = ':-)';
all_span[i].id = 'span_' + i;
current_p.appendChild(all_span[i]);
}
var container = document.getElementById('container');
document.getElementById('add').addEventListener('click', function()
{
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var create_p = document.createElement('p');
create_p.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")";
container.appendChild(create_p);
});
});
</script>
</body>
</html>
Something like this would be the easiest
let elements = document.querySelectorAll('p');
elements.forEach((el) => {
el.innerHTML = '<span>Added Span</span>';
});
Put that in a function that you call every time you add an element.
Please or to participate in this conversation.