0

I wan to get the content within the < p > tag using jQuery. So I can have a Java variable with each players name. The jquery code sets playerN1 as a blank string instead of the players name. I was wondering why the text() was not grabbing the players name (whats within the < p > tags)?

<!-- HTML -->
<div class="match1">
  <div id="m1.p1" class="col3 first last bracket_player1">
    <p class="name">Player1 Name</p>
  </div>
  <div id="m1.p2" class="col3 first last bracket_player2">
    <p class="name">Player2 Name</p></div>
  </div>
</div>
<div class="match2">
  <div id="m2.p1" class="col3 first last bracket_player1">
    <p class="name">Player1 Name</p>
  </div>
  <div id="m2.p2" class="col3 first last bracket_player2">
    <p class="name">Player2 Name</p></div>
  </div>
</div>

 

// The jQuery
for (i = 0; i < 7; i++)
{
   var match = "m" + i;
   var elementID = "#"+match+".p1 "+"p";
   var playerN1 = $(elementID).text();
   console.log(elementID);
   console.log(playerN1);
}
krizzo
  • 1,823
  • 5
  • 30
  • 52
  • You can't have a `.` in an ID. – Evan Davis Apr 16 '12 at 20:26
  • 2
    @Mathletics: The `.` is a valid ID character, but you need to escape it in the selector. EDIT: As show in [@Rocket's answer](http://stackoverflow.com/a/10181194/1106925). –  Apr 16 '12 at 20:28
  • @Mathletics: Technically, you can: http://stackoverflow.com/a/79022 I wouldn't suggest it, however. – gen_Eric Apr 16 '12 at 20:29

4 Answers4

6

It's because of the . in the ID. #m1.p1 is interpreted as ID=m1 AND class=p1. You need to either escape the . (with 2 \s).

var elementID = "#"+match+"\\.p1 "+"p";

Or use the [id=""] selector.

var elementID = "[id='"+match+".p1'] "+"p";
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Yeah I was worried that might cause an issue. Thanks for sending the link to the ID selector. This is my first time using jQuery. – krizzo Apr 16 '12 at 22:13
2

Why aren't you just grabbing them like this:

$('p.name').each(function() {
    console.log($(this).text());
});​
j08691
  • 204,283
  • 31
  • 260
  • 272
  • I need to keep tract of the matches as well which is why I couldn't just grab by .name thanks though. – krizzo Apr 16 '12 at 22:15
2

You could try to use html() instead of text() but I have a feeling the problem is with the . in the ID. I am not certain that is a valid character for an ID.

John Fable
  • 1,081
  • 7
  • 11
2

To grab the value of each element with the class 'name' you would just loop through them:

$('.name').each(function(){
    var thisPlayer = this.text();
    console.log(thisPlayer);
});
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119