# jQuery replace HTML

In a portion of my code to get a "report view" where the element is different (textarea becomes a div or span) and use the same data with newlines I replace the new lines with page breaks.

Currently the function I use:

$.each($('[id^="mytext-text"]'),(i,e)=>{$(e).html($(e).html().replace(/\n/gm,'<br>'))})


I often find myself using this same format for replacing other things, i.e.,

$(e).text($(e).text+'more text');


Is there a better way (either about using line breaks or about the .text(.text())? I've seen suggestions to simply write your own function but I feel like that doesn't solve the generalized problem.

• The argument to .text() and .html() can be a function. It receives the old text/html as an argument, and returns the replacement. You don't need .each(), since it automatically loops, and calls the function for each element. – Barmar Jul 5 '17 at 20:17
• Oh jeez I guess it pays to read the documentation once in a while; but I wouldn't have guessed I could apply a selector to each of the texts independently like you suggested without each. So this just becomes $('[id^="mytext-text"]').text((i,e)=>e.replace(/\n/gm,'<br>')) ! – Cody Ｇ Jul 5 '17 at 20:26 • It should be (e) =>. The first argument is the old text. – Barmar Jul 5 '17 at 20:31 • api.jquery.com/text/#text-function but it's not D: ! – Cody Ｇ Jul 5 '17 at 20:35 • Oops, I misremembered. – Barmar Jul 5 '17 at 20:37 ## 2 Answers As Barmar explained in his comment, you can use the function as argument to text() and html(). These methods iterate over all the elements matched by selector so, there is no need of each. Also, m-multiline flag is not required in the regex and can be removed. Final Code: $('[id^="mytext-text"]').html((index, html) => html.replace(/\n/g, '<br />'));


You could write a jQuery function that takes the method name and a function something like this completely unverified code:

jQuery.fn.replace = function replace(methodName, replacerFunc) {
return this.each(function() {
var $this =$(this);
var originalValue = $this[methodName](); var newValue = replacerFunc( originalValue);$this[methodName]( newValue );
}
}


And then calling it something like:

$('my-selector').replace('html', (v) => v.replace(/\n/gm,'<br>') );$('my-selector').replace('text', (v) => v + 'more text' );