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?

3
  • What is html of the div ? Commented Jun 9, 2016 at 9:39
  • @MairajAhmad let me post it Commented Jun 9, 2016 at 9:40
  • Your code works, make sure that myid is unique Commented Jun 9, 2016 at 9:45

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

5 Comments

thanks! but may I know why did .text and not .html? for future reference.
@hungrykoala : in your case both will be work since there is no html element inside
@hungrykoala put the text in span and you will see the difference
@guradio : that would be easy to understand :)
Refer following JSFiddle for reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.