Search code examples
jqueryprefix

jQuery. Prefix selector for various items


How to optimize this?

$('link[href="dir/style.css"]').attr("href", "dir/style2.css");
$('link[href="../../dir/style.css"]').attr("href", "../../dir/style2.css");
jQuery('link[href="../dir/style.css"]').attr("href", "../dir/style2.css");

Solution

  • You could do something like this:

    $('link[href*="dir/style.css"]').attr('href', function(i, oldHref) {
        return oldHref.replace('dir/style.css', 'dir/style2.css');
    });
    

    That uses the attribute-contains selector to select the elements, then passes a function to the call to .attr() to return the updated value.