823g4n8901
823g4n8901

Reputation: 139

JQuery Multiple selectors :first and :contains text()

var text = $('span:first:contains("From:")').siblings(span).text()

I want to select only the text whose sibling is the first span containing the text 'From:'. There is a second "From:" on the page and so the above query without ':first' works without error but it returns both texts. I just want the text related to the first instance of 'From:'. In xpath I think I could just add a [0] on the end. But I don't know how to 'nest' the :first selector (pseudo selector?). I'm new at jquery.

Upvotes: 0

Views: 170

Answers (2)

823g4n8901
823g4n8901

Reputation: 139

I was able to get it to work using a filter:

var text = $('span:contains("From:")').filter(function() {
      return $(this).text();
    }).first().siblings('span').text();

Upvotes: 0

Nikola.grancharov
Nikola.grancharov

Reputation: 672

Maybe you should share your HTML structure so we have better understanding of what you are trying to do.

From your explanation I understand you are trying to do this:

$(document).ready(() => {
    var text = $('span:contains("From:"):first').siblings('span').text();
    
  $('.display').text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span>Testing From: text 1 </span>
  <span>Sibling of text 1</span>
</div>
<div>
  <span>Testing From: text 2 </span>
  <span>Sibling of text 2</span>
</div>
<div>
  <span>Testing From: text 3 </span>
  <span>Sibling of text 3</span>
</div>

<hr>

<div class="display"></div>

it is almost the same as your code, but I have switched the places of the ":first" selector and the ":contains". But maybe I did not understand what you are explaining.

Upvotes: 1

Related Questions