0

this might be pretty noob, but there's this scenario where I can't find out the jquery selector I need.... So, let the html be like

<span style="color:red;">Gender:</span>Drama<br>
<span style="color:red;">Country:</span>USA<br>

What jquery selector should I use to get "Drama"? Thanks in advance

glezo
  • 742
  • 2
  • 9
  • 22
  • 1
    Since "Drama" is not an `HTMLElement`, you're gonna need https://api.jquery.com/contents/ – haim770 Feb 19 '17 at 20:24
  • You can find answer [here](http://stackoverflow.com/questions/6388507/use-jquery-to-select-text-not-in-an-element) – tkhuynh Feb 19 '17 at 20:45

3 Answers3

1

First you need to identify the <span> element and then get the text node right after it. Since your span elements don't have anything unique, you can use the order they're found in the parent element to identify them.

You can use pseudo-selectors such as :first-child or :nth-child to do so.

Once you've identified the span, you need to select the next node and retrieve its value.

One example:

console.log($('span:first-child')[0].nextSibling.nodeValue)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span style="color:red;">Gender:</span>Drama<br>
<span style="color:red;">Country:</span>USA<br>
</div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
motanelu
  • 3,945
  • 1
  • 14
  • 21
  • Thank u so much, @motanelu. I slightly modified your selector to achieve my needs: `alert($('span:contains("Gender")')[0].nextSibling.nodeValue);` – glezo Feb 25 '17 at 15:52
0

Your question is not very clear.

I suppose your content has a parent (<p> ?) I have the feeling that you're trying to do something in a complicated way, and that it could be more simple.

Why don't you put the content you have to select in other spans ? :

var textContent = new Array();
$('p .selector').each(function() {
  textContent.push($(this).text());
});

console.log(textContent[0]);
console.log(textContent[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
    <span style="color:red;">Gender:</span><span class="selector">Drama</span><br>
    <span style="color:red;">Country:</span><span class="selector">USA</span><br>
</p>
migli
  • 2,692
  • 27
  • 32
  • the question is **very clear** : I cannot modify the html. As I stated, I need to parse and extract the specified token as it comes. – glezo Feb 25 '17 at 15:50
0

Based on the answer of @montalenu , I achieved my goal by means of alert($('span:contains("Gender")')[0].nextSibling.nodeValue)‌​;

glezo
  • 742
  • 2
  • 9
  • 22