Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Banned
    Join Date
    Aug 2007
    Posts
    39
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Replace links on a page with javascript

    Say on my page I have <img src="http://example.com/a.gif"><a href="http://example.com"></a>

    How would I change http://example.com with javascript.

    I tried replacing it with document.write search for example.com but it wouldnt work..

    document.write(str.replace(/example.com/, "example2.com"));

    Any ideas?

  • #2
    Banned
    Join Date
    May 2006
    Location
    England
    Posts
    664
    Thanks
    0
    Thanked 84 Times in 84 Posts
    Quote Originally Posted by I_Love_Privacy View Post
    Say on my page I have <img src="http://example.com/a.gif"><a href="http://example.com"></a>

    How would I change http://example.com with javascript.

    I tried replacing it with document.write search for example.com but it wouldnt work..

    document.write(str.replace(/example.com/, "example2.com"));

    Any ideas?
    You need to assign each element an ID attribute, then use document.getElementById to address each element and write to its src or href property as appropriate.

  • #3
    Senior Coder
    Join Date
    Feb 2003
    Posts
    1,665
    Thanks
    0
    Thanked 27 Times in 25 Posts
    if you don't need to target specific images and anchors, you could simply loop/iterate through img and [/i]a[/i] elements, checking the src and href values respectively, changing instances of example.com to example2.com.

    (rough) e.g.
    Code:
    var aEls = document.getElementsByTagName('a');
    for (var i = 0, aEl; aEl = aEls[i]; i++) {
    	aEl.href = aEl.href.replace('example.com','example2.com');
    			
    }
    
    var imgEls = document.getElementsByTagName('img');
    for (var i = 0, imgEl; imgEl = imgEls[i]; i++) {
    	imgEl.src = imgEl.src.replace('example.com','example2.com');
    			
    }
    Alternatively, if you want to be more specific, you can still do so without needing to add any attributes to the targeted images and anchors, by targeting them as a child of a parent element.

    (rough) e.g.
    Code:
    var aEls = document.getElementById('targtDiv').getElementsByTagName('a');
    for (var i = 0, aEl; aEl = aEls[i]; i++) {
    	aEl.href = aEl.href.replace('example.com','example2.com');
    			
    }
    
    var imgEls = document.getElementById('targtDiv').getElementsByTagName('img');
    for (var i = 0, imgEl; imgEl = imgEls[i]; i++) {
    	imgEl.src = imgEl.src.replace('example.com','example2.com');
    			
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •