Search code examples
javascriptjqueryhtmlreplacestring-matching

How can I reuse result from JQuery for javascript textual matching?


I have html elements coming into function as string, then I am injecting elements into it as string however to my surprise it didn't work.

something like:

var replacement = $(row).find('td:last').append("<script type=\"text/javascript\"> function remove" + override.SessionKey + "(){ $('tr[session-key=\"" + override.SessionKey + "\"]').remove(); }</script><input type=\"button\" value = \"Remove\" onClick=\"remove" + override.SessionKey + "()\" />")

row.replace($(row).find('td:last')[0],replacement[0])

After some further investigation I have narrowed it down to matching failing in replace function, basically after you search with JQuery result cannot be used for textual matching

Here is an example of what I mean:

var r = "<tr class=\"hide\" session-key=\"SessionProductDataMotorEnrichmentSagaFactorScore\" session-key-data-type=\"Decimal\"><td id=\"tdDisplayName91\">SagaFactorScore</td><td id=\"tdValue91\"></td></tr>"

$('div').text(r.indexOf($(r).find('td:last')[0]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div></div>

One would expect to always have a match as I am using contents of original html string.

How can I reuse result from JQuery for textual matching?


Solution

  • I think you're looking for .outerHTML:

    var r = "<tr class=\"hide\" session-key=\"SessionProductDataMotorEnrichmentSagaFactorScore\" session-key-data-type=\"Decimal\"><td id=\"tdDisplayName91\">SagaFactorScore</td><td id=\"tdValue91\"></td></tr>"
    
    $('div').text(r.indexOf($(r).find('td:last')[0].outerHTML));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <div></div>