Apply anchor tag to all h3 tag below class

I am trying to find a way to add an anchor tag to the whole h3 tag. The content is dynamic.

I want to add dynamic anchor tag for all h3 tags

<div class="class1">
    <h2>Main heading</h2>
    <h3>Heading1</h3>
    <h1>some content1</h1>
    <h3>Heading2</h3>
    <h1>some content2</h1>
    <h3>Heading3</h3>
    <h1>some content3</h1>
</div>

      

I tried under JQuery code but didn't create anything

$("h3.class1").append('<h3>');
var al = $("h3.class1 >");

al.append('<a href="#"></a>');

      

+3


source to share


4 answers


$('div.class1 h3').each(function (){
            $(this).wrap('<a />');
        });

      



+2


source


Use wrap

:

Wrap your HTML structure around each element in a set of matched elements.

$('.class1 h3').wrap('<a />');

      



This will be wrap

everything h3

inside the .class1

tag anchor

.

DEMO

+2


source


Try wrapInner ()

$('.class1 h3').wrapInner('<a href="#"></a>')
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="class1">
  <h2>Main heading</h2>
  <h3>Heading1</h3>
  <h1>some content1</h1>
  <h3>Heading2</h3>
  <h1>some content2</h1>
  <h3>Heading3</h3>
  <h1>some content3</h1>
</div>
      

Run code


+2


source


You can use a callback function .html()

to achieve this goal:

function Type: Function (Integer index, htmlString oldhtml) => htmlString Function that returns HTML content to set. Gets the index position of the element in the set and the old HTML value as arguments. jQuery frees the element before calling the function; use the oldhtml argument to link to previous content. Within a function, this refers to the current item in the set.

$('.class1 h3').html(function(i,oldhtml){
  return '<a href="#">'+ oldhtml +'</a>' ; 
});

      

0


source







All Articles