Search code examples
javascriptjqueryhtmlreplacehref

replace href text in HTML using Javascript


Is it possible to use Javascript to change the a href value in the following code from href="http://**store**.mystitexxx.co.nz" to href="http://**www**.mystitexxx.co.nz"? It needs to be specific to this DIV or image, ie not global

<div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>

Solution

  • Gee, it seems like all the other answers are pretty complicated.

    It's simple:

    jQuery('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');
    

    Or, if you don't know where to put this / how to include it, then:

    Between your <head> and </head> tags, add this:

    <script>
        jQuery(function($) {
            $('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');
        }); 
    </script>
    

    And, if you don't already have jQuery loading, then just add it in like so (again, between <head> tags):

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script>
        jQuery(function($) {
            $('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');
        }); 
    </script>