Jascha Goltermann
Jascha Goltermann

Reputation: 1124

Best way to turn header elements into links using jQuery

I would like to turn all headlines inside a WordPress post into links automatically without using a plugin.

The HTML structure of a Wordpress post is basically this:

<article>
  <p>Text</p>
  <h2>Headline</h2>
  <p>More text</p>
  <h3>Another headline</h3>
  <p>Some more text</p>
</article>

Now I have the following jQuery to find all instances of h2 and h3 and turn them into links:

$('article h2').each(function(){

    $(this).replaceWith( "<a href='#' class='something'><h2>" + $(this).html() + "</h2></a>" );

});

$('article h3').each(function(){

    $(this).replaceWith( "<a href='#' class='something'><h3>" + $(this).html() + "</h3></a>" );

});

It works perfectly fine but there must be a more elegant and more performant way.

I don't actually know how to code in jQuery and have put together the code above by using bits of code I found in other answers. You can test the code above on jsFiddle.

Upvotes: 1

Views: 90

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

There's two tweaks you can make to improve the logic.

Firstly, include all headers in a single selector using :header. Secondly you can just use wrap() to place the existing content within an a element. Try this:

$('article :header').wrap('<a href="#" class="something"></a>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
  <p>Text</p>
  <h2>Headline</h2>
  <p>More text</p>
  <h3>Another headline</h3>
  <p>Some more text</p>
</article>

Upvotes: 1

Related Questions