Chris
Chris

Reputation: 453

Trying to prepend a <h2> before the first-child element of a set of sub elements

I have the following markup:

<ul class="expertise-list">
  <li>
    <p>Some text</p>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
  </li>
  <li>
    <p>Some text</p>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
  </li>
  <li>
    <p>Some text</p>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
  </li>
</ul>

I simply want to include a header before the first div, within each li. For example:

<ul class="expertise-list">
  <li>
    <p>Some text</p>
    <h2>Case title</h2>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
  </li>
  <li>
    <p>Some text</p>
    <h2>Case title</h2>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
  </li>
  <li>
    <p>Some text</p>
    <h2>Case title</h2>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
    <div>Case title</div>
  </li>
</ul>

I have tried experimenting with the following jquery, but I have only managed to get a title to appear on the first list item:

$('.expertise-list li div:first-child').before('<h2>Cases</h2>');

I'm sure this is something really simple to achieve! Thanks in advance!

Upvotes: 0

Views: 95

Answers (3)

Amit Joki
Amit Joki

Reputation: 59272

You can just append after <p>

$('.expertise-list li p').after('<h2>Cases</h2>');

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : You can use .after() for p tag in li

$('.expertise-list li p').after('<h2>Cases</h2>');

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

In your code p is the first-child but not divs. So you can use first-of-type:

$('.expertise-list li div:first-of-type').before('<h2>Cases</h2>');

Upvotes: 3

Related Questions