TovrikTheThird
TovrikTheThird

Reputation: 501

How to grab specific <p> when multiple at same level?

I have an html structure like this:

<div class="content">
    <h4>Available since...</h4>
    <div class="markdown">
        <p>Version 1</p>
    </div>
    <h4>Accessible by...</h4>
    <div class="markdown">
        <p>SOME TEXT I NEED TO ANALYZE</p>
    </div>
    <h4>Description</h4>
    <div class="markdown">
        <p>blah blah blah</p>
    </div>
</div>

I want to get the text in the second p-tag (SOME TEXT I NEED TO ANALYZE). I have multiple sections like this that I will be looping through and comparing those sections.

Upvotes: 0

Views: 29

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can use eq()

var text = $('.content > .markdown > p').eq(1).text();
console.log(text)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <h4>Available since...</h4>
  <div class="markdown">
    <p>Version 1</p>
  </div>
  <h4>Accessible by...</h4>
  <div class="markdown">
    <p>SOME TEXT I NEED TO ANALYZE</p>
  </div>
  <h4>Description</h4>
  <div class="markdown">
    <p>blah blah blah</p>
  </div>
</div>

Or for multiple .content divs to find second p in each one, you can use each() and check index

$('.content').each(function() {
  $(this).find('.markdown > p').each(function(i) {
    if (i == 1) console.log($(this).text());
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <h4>Available since...</h4>
  <div class="markdown">
    <p>Version 1</p>
  </div>
  <h4>Accessible by...</h4>
  <div class="markdown">
    <p>SOME TEXT I NEED TO ANALYZE</p>
  </div>
  <h4>Description</h4>
  <div class="markdown">
    <p>blah blah blah</p>
  </div>
</div>


<div class="content">
  <h4>Available since...</h4>
  <div class="markdown">
    <p>Version 1</p>
  </div>
  <h4>Accessible by...</h4>
  <div class="markdown">
    <p>SOME Lorem ipsum</p>
  </div>
  <h4>Description</h4>
  <div class="markdown">
    <p>blah blah blah</p>
  </div>
</div>

Upvotes: 2

Related Questions