eapo
eapo

Reputation: 1081

Elegant way to extract specific text from between HTML nodes?

From the following string I need the dynamically changing "6.903" number to make calculation with.

Is there some regular expression or some jQuery trick to do that easily or elegantly?

<a href="javascript:void(0)" class="" id="buddyTrigger">
38.760&nbsp;<img border="0" align="absmiddle" alt="Arany" src="/img/symbols/res2.gif">
&nbsp;&nbsp;5&nbsp;<img border="0" align="absmiddle" alt="Pokolkristály" src="/img/symbols/res3.gif">
&nbsp;&nbsp;220&nbsp;<img border="0" align="absmiddle" alt="Szilánk" src="/img/symbols/res_splinters.png">
&nbsp;&nbsp;91&nbsp;/&nbsp;125&nbsp;<img border="0" align="absmiddle" alt="Akciópont" src="/img/symbols/ap.gif">
&nbsp;&nbsp;6.903&nbsp;/&nbsp;82.100&nbsp;<img border="0" align="absmiddle" alt="Életerő" src="/img/symbols/herz.png">
&nbsp;&nbsp;<img border="0" align="absmiddle" alt="Szint" src="/img/symbols/level.gif">&nbsp;41    &nbsp;&nbsp;
<img border="0" align="absmiddle" alt="Harci érték" src="/img/symbols/fightvalue.gif">&nbsp;878</a>

Here is my code as lenghty solution, can I simplify somehow?

<script type="text/javascript">
    var dataIn=$('#infobar div.gold').html();
    var dataPrep2Split=dataIn.replace(/<img(.*)>/g,';');
    var dataSplit=dataPrep2Split.split(';');
    var myData2Int=parseInt(dataSplit[18].replace('.',''));
    if(myData2Int<=10000) {
        $('#player').find('button.btn').remove();
        var putBack=dataIn.replace(dataSplit[18],'<span class="newmessage">'+dataSplit[18]+'</span>');
        $('#infobar div.gold').html(putBack);
    }
</script>

Upvotes: 1

Views: 160

Answers (1)

Brock Adams
Brock Adams

Reputation: 93493

Use DOM methods; replacing things using .html() often breaks page features. Also, that regex is liable to break with the smallest change.

You're trying to grab the Life value right? And that ends with the <img> with alt="Életero".

So that text node is (based on the Q code):

var lifeValTxtNd    = $("#buddyTrigger img[alt='Életero']")[0].previousSibling;


And this gets 6903 from the contents like 6.903 / 82.100:

var lifeVal         = $.trim (lifeValTxtNd.nodeValue)
                    .replace (/^\s*(\d*)\.?(\d+)\s*\/.+$/, "$1$2")
                    ;
lifeVal             = parseInt (lifeVal, 10);


Then to wrap that section in a span use:

$("#buddyTrigger img[alt='Életero']").before (
    '<span class="newmessage">' + lifeValTxtNd.nodeValue + '</span>'
);

lifeValTxtNd.parentNode.removeChild (lifeValTxtNd);


Doing it this way:

  1. Won't break any event listeners on the page.
  2. Is less susceptible to changes in the page layout/content.
  3. Is easier to understand and maintain.
  4. Will run faster, if performance is a factor.

Upvotes: 2

Related Questions