Search code examples
jqueryhrefaddclass

How can i achieve this with JQuery


I currently have this in my document

$(document).ready(function(){
     $("[href$='.html']").addClass('html');
     $("[href$='.pdf']").addClass('pdf');
});

which styles any links that have an html extension and pdf extension. If the url has the extension it displays an image before the link. I want to make it only style those in an unordered list I have with a class of "dlist." How can I do this? I tried adding it before the [href] but nothing happened. Problem I'm having is it's styling other links in articles and not only the download section like I need it to.


Solution

  • $(document).ready(function(){
         $("ul.dlist a[href$='.html']").addClass('html');
         $("ul.dlist a[href$='.pdf']").addClass('pdf');
    });
    

    You'll need a space between ul.dlist and a[href$='.pdf'].

    The space is the descendant-selector[docs].

    Also, you'll notice that I added a before the [href...] selector. This will be more efficient because it will not need to analyze all elements, but rather just the a elements.