0

I have this code:

HTML:

<td id="myid">something</td>

JavaScript:

var test = $("#myid").html();
console.log(test);
if(test == "something"){
alert("Great!");
}

my problem here is that in the console the word something appears but when it is on the condition they do not match, maybe because the .html value retrieved is not a string. So I want to know how do I convert it to string?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
hungrykoala
  • 1,083
  • 1
  • 13
  • 28

1 Answers1

2

Use text() method to get text content and String#trim() ( or jQuery.trim()) to remove the white space from both end of string.

var test = $("#myid").text().trim();
console.log(test);
if (test == "something") {
  alert("Great!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="myid">something</td>
  </tr>
</table>

For understanding the difference Refer : What is the difference between jQuery: text() and html() ?

console.log(
  $("#myid").text(),
  $("#myid").html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="myid"><span>something</span>
    </td>
  </tr>
</table>
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188