'Adding HTML via JS to a specific child-Element

I have a very specific situation where I have ~50 child-divs which I cannot influence directly, that is, I cannot add classes or ids to one specific child-div nor alter the div via HTML because they are created automatically. They appear in a simple grid/flexbox, two boxes next to each other. I already altered some of them with nth-child, but now I want to add individual headlines between f.ex. div 30 and 31.

Up until now, when I wanted some of the fields to be bigger, I addressed one of the child-divs directly via nth-child.

Here's the basic structure:

    <div class="parent">
      {$content} // basically <div>{$single-box-content}</div>
   </div>

And the CSS I currently use:

 .parent {
    width: 800px;
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    }
    
    .parent:nth-child(10) {
    width:800px;
    }

That worked quite well. However, now that I want to have a headline above one of the divs (not inside), it doesn't work. When I try this:

.parent:nth-child(31):before {
content: "Headline";
display: block;
}

It appears inside the child-div, not above it. I cannot add a div to the HTML part, since all of them are created automatically in the backend (it's a form).

I wondered if it is possible to use JavaScript with some element.innerHTML, but I am at the very beginning of learning JS and I couldn't find anything (I could adapt) to address specific child-Elements in JS. Is there a frontend solution to my problem?



Solution 1:[1]

With JS you can add classes, IDs, append HTML-elements to the DOM and so much more.

Below shows you how to both to insert an h2, but also how to add a class to an element of your choosing - I used :nth-child(3) for illustration purposes, but you can just swap that with :nth-child(31). The code is explained in comments in the snippet.

// finding the child element with nth-child selector
let selected = document.querySelector('.parent:nth-child(3)');

// giving it a class name
selected.classList.add('parentClass');

// creating a h2 element
let header = document.createElement("h2");
// the text inside the h2 element
let headerText = document.createTextNode("headline");

// appending the text to the h2 element
header.append(headerText);

// giving the child a class name
header.classList.add('childClass');

// appending the headline above/before the selected element 
selected.parentNode.insertBefore(header, selected);
/* the class applied with JS */

.parentClass {
  background-color: red;
}

.childClass {
background-color: limegreen;
}
<div class="parent">parent 1</div>
<div class="parent">parent 2</div>
<div class="parent">parent 3</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1