0

I have some simple Javascript (and Jquery) that runs when an <a> element is clicked

$("a[href^='#']").click(function(e)
{
    e.preventDefault();

    var element = $($(this).attr("href"));

    var position;

    // If the href refers to #test

    if(element == $("#test"))
    {
      position = element.offset() + element.height();

      console.log("Successful");
    }

    else
    {
      position = element.offset().top;
    }
}

The if comparison never seems to work even when the value of element is equal to $("#test") in the console and, therefore, it always jumps to the else condition.

It may be worth mentioning that when using breakpoints, both values (element and $("#test")) are equal to the following

w.fn.init [section#test.main.special]

What is the reason my comparison is not working?

  • Duplicate? https://stackoverflow.com/q/2407825/5768908 – Gerardo Furtado Sep 19 '18 at 06:52
  • What is `var element = $($(this).attr("href"))` supposed to achieve? – connexo Sep 19 '18 at 06:54
  • `$("#test")` is a jQuery selector that hasn't been paired with any functionality. If you wish to do a check directly on the attribute, then compare it to a string version of the attribute directly. `if(element == "#test") { //code goes here }`. – Martin Sep 19 '18 at 06:55

1 Answers1

1

use it as a string

$("a[href^='#']").click(function(e)
{
    e.preventDefault();

    var getHref = $(this).attr("href").trim();

    var element = $(getHref);

    var position;

    // If the href refers to #test

    if(getHref == "#test")
    {
      position = element.offset().top + element.height();

      console.log("Successful");
    }

    else
    {
      position = element.offset().top;
    }
}
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • I think this is correct. Besides, I would use the triple equals for compare. if(element === "#test"). That way, you are making sure types equality. – ILoveYouDrZaius Sep 19 '18 at 06:56
  • @ILoveYouDrZaius that depends what the variable `element` ends up being *"exactly"*. Using strict equals would make it have to be two strings in comparison. The double equal is more abstract and allows different types to be compared with one another. – Martin Sep 19 '18 at 07:00
  • @Kaiido sorry I can't get your point .. what is wrong when the output of `element` href be `#test` and then use it as an id like `$(element)` `$('#test')` – Mohamed-Yousef Sep 19 '18 at 07:08