Nadav S.
Nadav S.

Reputation: 2459

Rewriting specific links with javascript, except links to specific directory

I have a page which contains links, that needed to be rewrited with Javascript. All the links in the div id="container" are needed to be rewrited from "post=post-number-234" to "?id=blog&post=post-number-234".

Currently I have this script:

<script type="text/javascript">
<!--
var content = document.getElementById('content');
var list = div.getElementsByTagName("A");
for( var i = 0; i < list.length; i++ ) 
{ 
  document.links[i].href = '?id=blog&' + document.links[i].href
}
// -->
</script>

This works fine. But I have links to images, that are used by Fancybook. All these links are originally linked to "img/image-name.jpg". But now fancybook doesn't work because it searches for images inside "?id=blog&img/image-name.jpg".

How can I apply rewriting to all the links inside the div "content", that are NOT linked to the directory "img"?

Thanks!

Upvotes: 0

Views: 141

Answers (3)

kalisjoshua
kalisjoshua

Reputation: 2496

Assuming that you have links similar to the following in your page:

<a href="img/name.jpg"><img src="img/name.jpg" /></a>
<a href="post=post-number-234">Post Title - by Author Maybe?</a>

If you are not going to be using a framework/library, such as jQuery or the like, you will obviously need to a little more heavy lifting and filter out want you don't want to change yourself. So something like:

<script>
var content = document.getElementById("content")
  , list = content.getElementsByTagName("a")
  , i = 0
  , len = list.length;

for (; i < len; i++) {
   // check for "img/" directory or image file-extensions (gif, jpg, jpeg, png)
   if (!/^img\/|\.(?:gif|jpg|jpeg|png)$/i.test(list[i].href)) {
       list[i].href = "?id=blog&" + list[i].href;
   }
}
</script>

Upvotes: 1

Andreas
Andreas

Reputation: 21911

This works fine

I doubt so...

First you get a DOM element with id "content". Then you try to get all the links from div what should fail with ReferenceError: div is not defined because its not defined anywhere (if not, you are not providing all the relevant code).

If that would be successful then you're going to iterate over the found links and access them by index. But from the wrong source. Instead of list you are using document.links

Summing all up...

<script>
    var container = document.getElementById("container"),
        links = container.getElementsByTagName("a"),
        i = links.length,
        href;

    while (i--) {
        href = links[i].href;

        if (href.indexOf("img/") > -1) {
            continue;
        }

        links[i].href = "?id=blog&" + href;
    }
</script>

Upvotes: 1

keune
keune

Reputation: 5795

Inside the loop, check if the href string contains 'img', and only modify it if not found.

if (document.links[i].href.indexOf('img') == -1) {
  document.links[i].href = '?id=blog&' + document.links[i].href;
}

Upvotes: 1

Related Questions