JQuery different content for the same class

I have 10 <p>tags in my html with class.rule

I want to change their text separately, without using a separate identifier, for example #rule1, #rule2, #rule3:

$('#rule1').text('Rule 1')
$('#rule2').text('Rule 2')
$('#rule3').text('Rule 3')

I just want one class to be selected in jQuery, but to edit the text of other tags <p>with the same class.

How should I do it?

+4
source share
8 answers

Try the following: -

$('p.rule').each(function( index ) {
  $(this).text("Rule" + (index + 1));
});

Fiddle

Documents

+6
source

text(), p , each(). , , . - , , :

$('p').text(function(i) {
  return 'Rule ' + (i + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
Hide result
+4

$('.foo').each(function( index ) {
    $(this).text("bar " + index);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
Hide result

DOM.

https://api.jquery.com/each/

+1

, ,

$('p.rule').text(function() {
  return 'Rule ' + ($(this).index(".rule")+1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="rule"></p>
<p class="notrule">Not a rule</p>
<p class="rule"></p>
<p class="rule"></p>
<p class="rule"></p>
Hide result
0

, , , .eq()

var rules = $(".rule");
rules.eq(0).text('Rule 1');
rules.eq(1).text('Rule 2');
rules.eq(2).text('Rule 3');

, .each(function)

var rules = $(".rule");
rules.each( function (index) {
    $(this).text('Rule ' + index);
});

.text(function)

var rules = $(".rule");
rules.text( function (index) {
    return 'Rule ' + index;
});
0

Just loop through each p tag using the code below. If you have a clear idea of ​​how to manipulate the p tag, then you need to use a separate identifier or rely on the order in which your P tags appear.

$('p.rule').each(function( index ) {
    $(this).html("P with index" + (index) );// you can accordingly add html or any other jquery operation based on order/index of your p tag
});
0
source

Use this:

$('p').each(function( index ) {
    $(this).text('Rule ' + (index + 1));
});
0
source

You can use rowIndx.

var rowIndx = this.id.substring(this.id.length,this.id.length - 1 );

$("p.rule"+rowIndx).each(function(i){
  
  $(this).text("rule" + (i+1));
  
 });
Run codeHide result
0
source

All Articles