2

I am creating a variable that is equal to the text of a <a> that has been clicked on, and then use the variable in an if / else statement but cant get it to work. I know the variable is right, and I know the function works because I can replace it with a "whatever.html" and it work. However I cant get the variable to work in its place:

   $(".themenu a").click(function(){
          var stuff = $(this);
          if (stuff == "Home"){
                 $.get("main.html", function(data){
                 $(".content").append(data);
          }, "html");
   }
2
  • If you want html to appear in your question quote it with the ` character (I've updated your question to do this). Commented Sep 19, 2011 at 6:20
  • I guess you have to change the second row to var stuff = $(this).text(); Commented Sep 19, 2011 at 6:22

5 Answers 5

6

$(this); will get you a jQuery object, not the text of it, so that won't be equal to "Home". Use

var stuff = $(this).text();

or

var stuff = $(this).html();
Sign up to request clarification or add additional context in comments.

Comments

4

You are setting your stuff variable to reference the jQuery object returned by $(this), when what you really want is the text of the element in that jQuery object like so:

var stuff = $(this).text();

EDIT: note that in your click handler this will be equal to the <a> element you could also do this:

var stuff = this.innerHTML;

Comments

2

Your selector selects the <a> node, which is an object. If you want to use it for comparison, you first have to get the value, ID or content of that tag.

var stuff = $(this);

Now, stuff contains a DOM object representing the <a href="url">Home</a> element. What you want is to extract the bit between the tags.

var innerStuff = stuff.text();

Or of course, directly:

var stuff = $(this).text();

Comments

0

You should do var stuff = $(this).text(); instead.

1 Comment

+1 to balance the unexplained -1 (don't know why this was voted down when it is correct, though it is a duplicate answer).
0

try:

var stuff = $(this).text();

1 Comment

+1 to balance the unexplained -1 (don't know why this was voted down when it is correct, though it is a duplicate answer).

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.