Using JavaScript, how to change Header to an H3 if it nested inside an H2?

I have this component called topComponent that has a title, body, and link. The Title is an H2.

<div class="topComponent"> 
        <div class="Wrapper">
            <h2 class="title">About The Eartht</h2>
            <div class="container htmlText">
             <p>Here is some information about the Earth..</p>
         </div>
            <div class="infoLink">
            <a href="........." target="_blank"</a>
            </div>
        </div>
    </div>

However, if this title header is nested inside another header that is an H2, then I am trying make this title header an h3. Basically let say there is an HTML like this:

    <h2 class="bigHeader">About The Earth Parent</h2> // Parent Header
    <div class="topComponent"> 
                <div class="Wrapper">
                    <h2 class="title">About The Eartht</h2>
                    <div class="container htmlText">
                     <p>Here is some information about the Earth..</p>
                 </div>
                    <div class="infoLink">
                    <a href="........." target="_blank"</a>
                    </div>
                </div>
            </div>

Here, there is a parent header called bigHeader that is an H2. So in this case, I want the title header to change to H3 instead of h2, since there is already a parent h2 on top.

Question: How can we determine if the title should be an h2 or h3 depending on if there was an H2 parent for this element through a script?

Here is the Javascript:

$(Wrapper).each(function(){
  var count = 0;
  $("h2").each(function(){
    if(count > 0)
    {
      $(this).replaceWith($('<h3>' + this.innerHTML + '</h3>'));
    }
    count++;
  });
});

The problem with the above code is that, it's changing the h2 headers outside of this component as well. I was hoping the changes will only happen within the Wrapper div. Not sure why it's not selecting the H2's only with in the wrapper.


Here is a simple solution.

var container = document.getElementById("container");
var h2 = container.getElementsByTagName("h2");

if(h2.length == 2){
  var h3 = document.createElement('h3');
  h3.innerText = h2.innerText
  h2[1].replaceWith(h3);
}
<div id="container">
  <h2 class="bigHeader">About The Earth Parent</h2> // Parent Header
  <div class="topComponent">
    <div class="Wrapper">
      <h2 class="title">About The Eartht</h2>
      <div class="container htmlText">
        <p>Here is some information about the Earth..</p>
      </div>
      <div class="infoLink">
        <a href="........." target="_blank" </a>
      </div>
    </div>
  </div>
</div>