Search code examples
jqueryhref

get element that is of class with specific href


This is the code I use to get element with a specific href value:

var myElement = $("a[href='http://www.stackoverflow.com']");

I would like to only get elements that are of class title. I tried this, but it didn't work.

var myElement = $(".title, a[href='http://www.stackoverflow.com']");

Any idea what am I missing?


Solution

  • Get rid of the , and use a selector like

    var myElement = $("a.title[href='http://www.stackoverflow.com']");
    

    Demo

    Above selector will select all a tags with a class of .title with href you've specified.

    The reason your selector failed is because when you use a , it will select all a tags with that href value and all elements with a class of .title which is not what you are looking for. Hence we write a.title which will select the a only if they have a title class.