My goal is to dynamically add a class to specific elements based on the presence of another class in elements below them.
Consider the following code snippet:
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
<button class="somebutton">Click Here</button>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
<image src="URL" />
I want to add a class "nomargin" to elements with the class "my-paragraph" if an element without that class is directly below it.
After implementing this logic, the final output would resemble the following:
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph nomargin">This is a sentence.</p>
<button class="somebutton">Click Here</button>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph nomargin">This is a sentence.</p>
<image src="URL" />
I've been struggling to come up with a solution for this problem using Vanilla JavaScript, and it's been challenging me for a few days now, causing some imposter syndrome feelings.
I believe starting with a for loop could be a good approach, but I'm stuck on the implementation logic. Any guidance or help would be greatly appreciated.