Search code examples
javascriptjqueryhtmlhref

Referencing href value and comparing to another


I have this:

var userName = "$('.home').children('.username').attr('href')";
$(".someclass[href*=userName]").parent().parent().addClass("extra-attribute");

I want to add "extra-attribute" to a class based on if it contains a match from the href being referenced. Is this set up right?


Solution

  • Your expression is a wrapped in as a string (Remove it) for the first one and for the second line you wrapped userName as a part of the selector not the value of userName variable.

    So Try:

    var userName = $('.home').children('.username').attr('href');
    $(".someclass[href*=" + userName + "]").parent().parent().addClass("extra-attribute");
    

    Also note that .attr('href') will get you the href of only the first userName anchor tag returned by the collection $('.home').children('.username'). Instead of doing .parent().parent() you can use closest('parentparentselector') provided your parent.parent has that selector and not its parent. That would let you change your html structure as well without changing your script in the future.