Search code examples
htmljqueryinsert

How can I insert an element into another for specific parent class only?


I have similar problem as mentioned HERE but need to add <span class="my-class" and </span around whole text inside h1, also need to add this for specific parent element class only: "ast-archive-entry-banner" (probably can skip "ast-container" class - see below).

So from this:

<section class="ast-archive-entry-banner">
 <div class="ast-container">
  <h1>Title</h1>
 </div>
</section>

to this:

<section class="ast-archive-entry-banner">
<div class="ast-container">
<h1><span class="my-class">Title</span></h1>
</div>
</section>

Will appreciate any help as I have no knowledge about jQuery and this is only solution that will work for me as I figured out looking for a solution last days.

Thanks!

Tried to change solution from link above but no success.


Solution

  • This script finds the h1 element within the specified section and wraps its content with a span element that has the class "my-class".

    $(document).ready(function() {
      $(".ast-archive-entry-banner h1").html(function() {
        return '<span class="my-class">' + $(this).text() + '</span>';
      });
    });
    .my-class {
      background: pink;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <section class="ast-archive-entry-banner">
      <div class="ast-container">
        <h1>Title</h1>
      </div>
    </section>