0

I have something like this:

<li id="machine" ><h1>Machine</h1></li>
<li id="player"><h1>Player</h1></li>

Showing this:

html after the jQuery

when I use jQuery to change the text to a number like this:

$("#machine").text(1);
$("#player").text(2);

it will change my h1 to normal tex like this:

html after the jQuery

How do I keep the h1 to be h1 after passing a number??

Jonathan
  • 6,507
  • 5
  • 37
  • 47
Alex
  • 75
  • 10

3 Answers3

2

You have to target the <h1> directly, otherwise it will remove all tags within the #machine or #player divs.

$("#machine h1").text(1);
$("#player h1").text(2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="machine"><h1>Machine</h1></li>
<li id="player"><h1>Player</h1></li>

Alternatively, put the id directly on the <h1> tags

$("#machine").text(1);
$("#player").text(2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><h1 id="machine">Machine</h1></li>
<li><h1 id="player">Player</h1></li>
Jonathan
  • 6,507
  • 5
  • 37
  • 47
1

text() replaces the complete contents of the tag/class/ID it's applied to, in your case this includes the h1tags, which are inside (i.e. contents of) the #machine and #playerelements.

But you can apply your jQuery to "#machine h1" to avoid that:

$("#machine h1").text(1);
Johannes
  • 64,305
  • 18
  • 73
  • 130
-1

You can instead use the html method $("#machine").html("<\h1> 1 </h1>");

Onejohi_
  • 41
  • 1
  • 1
  • 8