How to target each post shown on a View Topic phpBB page to inject HTML using Javascript

82 Views Asked by At

Ok so I have a phpBB forum where the image attachments or inline images (using an image link) in posts don't format how I want them to. I want them to be inline with each other, but not with the text that is before or after them. I don't want to rely on the user entering in manual line breaks in the post, as they often don't know to do it.

E.g. This is some text [I don't want the image here]

[I want the image here] [and another one here] [I don't want more text here]

[I want more text here]

I have this working, partly, but the code places a
tag before the very first image on the entire page, and after the last image on the entire page. I'd like it to apply to each individual post on the page, affecting the first and last image within each.

This is my current code: `

<script>
    var firstattachedimg = document.getElementsByClassName("inline-attachment")[0];
    firstattachedimg.insertAdjacentHTML('beforebegin', '<br>');
    
    var attachedimgs = document.getElementsByClassName("inline-attachment");
    for (var i = 0; i < attachedimgs.length; ++i) {
        var lastattachedimage = attachedimgs[i];
    }
    lastattachedimage.insertAdjacentHTML('afterend', '<br>');
</script>
`

My question is, how do I get that code to run per post on the View Topic page, rather than running for the entire page and not hitting the right images?

The live URL is harleyforums[dot]co[dot]nz if you'd like to have a look at it. The code is placed in the footer template file and runs only on the View Topic pages. And here's a direct link to an example post where you can see what it's hitting and what it's not: harleyforums[dot]co[dot]nz/viewtopic.php?p=651#p651

Thank you!!

1

There are 1 best solutions below

0
sikmah 66 On

Figured it out. For anyone who's curious, this seemed to do the trick:

<script>
var posts = document.getElementsByClassName("post");
for(var x=0; x < posts.length; x++)
{
var firstattachedimg = posts[x].getElementsByClassName("inline-attachment")[0];
firstattachedimg.insertAdjacentHTML('beforebegin', '<br>');
var attachedimgs = posts[x].getElementsByClassName("inline-attachment");
for (var i = 0; i < attachedimgs.length; ++i) {
var lastattachedimage = attachedimgs[i];
}
lastattachedimage.insertAdjacentHTML('afterend', '<br>');
}
</script>