Chordzone.org Chordzone.org - 5 months ago 12
jQuery Question

Find specific value inside a span tag

I am trying to find a specific word inside a span tag.

The

<span>
is inside a
<pre>
.

I want to get the "6" from the code below.

<span class="infos">Scale: Ab Major
Time Signature: 6/8
Tempo: 80
Suggested Strumming: DU,DU,DU,DU
</span>


I also want to get the "80" as well and put it into an
<input>
.

The values of
Tempo
and
Time Signature
keeps on varying, so a simple search and retrieve didn't work.

I have tried so many methods suggested on SO, but nothing seems to help me with it.

This is the code that came closest. But it didn't help.

<script>
$("span:contains('Tempo:')").html(function(_, html) {
return html.replace(/(Tempo:)/g, '<span class="tem">$1</span>');
});
</script>

<span class="infos">Scale: Ab Major
Time Signature: 6/8
Tempo: 80
Suggested Strumming: DU,DU,DU,DU
</span>


Any help is really appreciated.

Answer

I have modified the answer of Barmer to find the 'Time Signature' value.

I think this may help you.

$("span.infos").html(function(_, html) {
  var searchWord = 'Time Signature:';
  var searchWordlen = searchWord.length;
  var lastIndexofSearchWord = html.lastIndexOf(searchWord) + searchWordlen;
  var timeSignature = html.substring(lastIndexofSearchWord, html.lastIndexOf("/"));
  timeSignature = parseInt(timeSignature); //here is your value
  alert(timeSignature);
  return html.replace(/Tempo: (\d+)/, '<span class="tem">Tempo: <input name="tempo" value="$1"></span>');
});
.infos {
  white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="infos">Scale: Ab Major
 Time Signature: 6/8
 Tempo: 80
  Suggested Strumming: DU,DU,DU,DU
</span>