Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace part of an HREF attribute in a link with jQuery

I'm new to jQuery and I need to replace a part of an A HREF attribute in a link. More specifically, a piece of code that will remove the "-h" from "s1600-h" for a lightbox application:

In other words, turn s1600-h to s1600

Also, do I need to use $(function() or $(document).ready(function() before the piece of code?

like image 276
Jon Avatar asked Oct 16 '10 06:10

Jon


People also ask

How do I change the text anchor tag in jQuery?

With jQuery, you can use the text() method to replace the text of an anchors tag with a specific text.

Can we replace in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.

What will href =# do?

Definition and Usage. The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!


2 Answers

$(document).ready(function(){
    $('a').each(function(){
        this.href = this.href.replace('s1600-h', 's1600');
    });
});
like image 62
Bang Dao Avatar answered Sep 22 '22 06:09

Bang Dao


jQuery(document).ready(function() {
  jQuery('a').each(function(){
     this.href = this.href.replace('s1600-h', 's1600');
  }); 
});
like image 31
RichestSoft Avatar answered Sep 22 '22 06:09

RichestSoft