How do get contents of a p element one at a time

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! :)


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');
});

使用接受回调的text()版本作为第二个参数,并从回调中返回替换的内容

$('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>

你可以在.each上使用.each方法:

$('p').each(function (pEl) {
    var text = pEl.textContent;
});
链接地址: http://www.djcxy.com/p/83528.html

上一篇: Jquery“循环”迭代

下一篇: 如何一次获取ap元素的内容