If you have the first <h1> always in your first <div> , then both the answers given by Type and pratikwebdev will work. However, like the Vucko mentioned in the comment, if you have a situation like below, then only CSS will not help you.
<div class="box"> <div>bla bla bla</div> <div><h1>first h1 needs to be underlined</h1></div> <div>bla bla bla2</div> <div><h1>big bla bla bla but not underlined</h1></div> </div>
You can see that currently available CSS selectors work with only one movement , that is, from parent to child (ren) or to the next sibling (s), but not to the parent or element to the previous sibling (s). So, as soon as you select child (ren), there is no return to the parent level, or as soon as you select the next sibling (s), there is no return to the current element. This, in fact, makes CSS so fast.
Selectors Level 4 The draft offers a :has() pseudo-class that would allow checking the internal elements before choosing the next brother (s). However, browsers do not yet have this feature, they may not have it in the near future, and even when they do, it will be exclusive to the latest generation of browsers and will not be supported by the ones we have.
So what can be done? Well, you can put a specific class directly in the first <h1> using the .has() or :has() method, the jQuery selector or your own JavaScript function. I personally do not think jQuery is necessary for something easy.
CSS
.underlined { text-decoration: underline; }
JS:
(function(H1s){ var H1qty = H1s.length, grandParent, boxes = []; // Loop through H1s and add class name to first occuring H1 for(var i=0; i<H1qty; i++){ grandParent = H1s[i].parentNode.parentNode; if(grandParent.className === 'box' && boxes.indexOf(grandParent) < 0){ H1s[i].className = 'underlined'; boxes.push(grandParent); } } })(document.querySelectorAll('h1'));
A working example is here .