Replace all strings in dom element

2020-04-19 05:53发布

问题:

I've a piece of DOM like this

<table style="display:none;" id="risposta-campione">
<tr>
<td>
    <label>Risposta</label><textarea id="risposta_0000" name="risposta_0000" cols="35" rows="2"></textarea>
    <button type="button" onclick="cancellaRispostaDomanda('0000')" class="cancella-risposta"></button>
    <button type="button" onclick="aggiungiRispostaDomanda('0000')" class="aggiungi-risposta"></button>
</td>
</tr>
</table>

I want to replace all '0000' occurrences with jquery without getting each element.

Is this possible?

I tried this:

elem = $('#risposta-campione').text() // how convert dom to string?!
elem.replace('0000', 'hello');

with no solution :-/

回答1:

Use $('#risposta-campione').html().replace('0000', 'hello');



回答2:

strings = $('#risposta-campione').html();
strings = strings.replace(/0000/g,"hello");

this will replace all the occurance of 0000 to hello.



回答3:

Just use the html() function

elem = $('#risposta-campione').html()


回答4:

var text = $('#risposta-campione').html().replace(/0000/g, 'hello');  // g is case sensitive search in string

//Or

var text = $('#risposta-campione').html().replace(/0000/gi, 'hello');  // gi is case insensitive search in string


回答5:

Yes,it will not be efficient as if you were using direct element but it can be done in one line:

 $("#risposta-campione").html($("#risposta-campione").html().replace("0000", "your-new-text"));