-1

Using jQuery, I need to parse the contents of each <p> tag individually and then replace the text with the new text.

The code at the moment looks like:

str = $('p').text();
str = str.replace('yadayada','yada');
$('p').text(str);

This is currently getting the contents of all the <p> tags, concatenating them then replacing the massive block of text into each <p> which is close but not quite what I'd like it to do.

Is there a way to get the contents of each <p> block one at a time and replacing it with only it's contents? I do not know what ids or classes are being applied to them hence the need to use the generic tag.

Any help is much appreciated! :)

TomHill
  • 614
  • 1
  • 10
  • 26

3 Answers3

3

Use the text(fn)

A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

$('p').text(function(_ text){
    return text.replace('yadayada','yada');
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Use the text() version that accepts a callback as the second argument and return the replaced content from the callback

$('p').text(function(i, str) {
  return str.replace('yadayada', 'yada');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>yadayada-1</p>
<p>yadayada-2</p>
<p>yadayada-3</p>
<p>4</p>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You can use .each method on the colletion:

$('p').each(function (pEl) {
    var text = pEl.textContent;
});
Michał Miszczyszyn
  • 11,835
  • 2
  • 35
  • 53