Weiping
Weiping

Reputation: 53

Retaining CSS when changing text dynamically with javascript

I've been trying to randomize a number with a button, but every time I clicked the button, the number randomizes, but the text loses it's CSS style.

CSS

.numberStyle {
  padding: 10px 10px 10px 10px;
  color: blue;
}

.numberStyle span {
  font-size: 100px;
}

Html

<class id="number1" class="numberStyle"><span>1</span></class>
<input type="button" value="MATCH!" style="font-size:50px;"></input>

Javascript

function randomize() {
  no1 = Math.ceil(Math.random() * 3);
}

function print() {
  $("#number1").text(no1);
}

$().ready(function() {

  $(":input").click(function() {
    randomize()
    print()
    alert("Change")
  })

})

my JSFiddle link : https://jsfiddle.net/he4rtbr0ken/9jfud4nz/2/

Upvotes: 1

Views: 44

Answers (3)

Weiping
Weiping

Reputation: 53

Thanks for the answer!

I've targeted <span> element and it works.

replaced print() function with the codes below.

function print() {
  $("#number1 > span").text(no1);
}

Upvotes: 0

Jeff Tabachnick
Jeff Tabachnick

Reputation: 153

You want to change the text within the span rather than #number1

function print() {
    $("span").text(no1);
}

Upvotes: 1

Damon
Damon

Reputation: 4336

You are targeting the parent of the <span> element and then changing its text which is essentially removing the span and replacing it with only the number. You can fix this by targeting the span or including the span in the text you are adding.

Upvotes: 0

Related Questions