script only in a div

Asked

Viewed 84 times

0

<script type="text/javascript">
    onmousemove = function adfy() {
        adfy_id = '.html'; //replace with your ID
        for (var i = 0; i < document.links.length; i++) {
            var hrefer = document.links[i].href;
            if (hrefer.match(".html") || hrefer.match("javascript:") || hrefer.match("#")) {
                document.links[i].href = document.links[i].href;
            } else {
                document.links[i].href = document.links[i].href + adfy_id;
            }
        }
    }

</script>
<a href="test.html">com .html</a>
<a href="test">sem .html</a>

I’m using this codido adfly para por . html in the links of my site, there are more than 300 so I don’t want to do it manually. It worked very well, but it is disturbing other links that do not need it.

I was wondering if there’s any way to make it work in just one div?

  • I don’t have time to answer now, but 1 question: your page has dynamic content or HTML is the same since the page loads. adfy_id is declared somewhere?

  • HTML, not just in the function

2 answers

1


Add an attribute of 'id' (with a name, of course) for your div and use the method document.getElementById to capture her. Therefore, you will not have the property links in its element and will have to use HTMLElement.prototype.getElementsByTagName to pick up the hyperlinks from div in an array.

If possible, could explain why to use the event onmousemove to update hyperlinks? This can cause slowdowns...

window['onmousemove'] = (function adfy() {

    /* Href file extension */
    var fileFormat = '.html';

    var div = document.getElementById("id"),
        links = div.getElementsByTagName("a");

    /* Iterate through the links */
    for (var i = 0, a; a = links[i]; i++) {
        if (a['href'].match(".html") || a['href'].match("javascript:") || a['href'].match("#")) {
            a.href = a['href'];
        } else a.href = a['href'] + fileFormat;
    }

});
<div id="id">
  <a href="test.html">com .html</a>
  <a href="test">sem .html</a>
</div>

0

Add to whatever links you have .html a class, in this case I added .addHtml. So Function will only work in these elements.

<a href="test.html" class="addHtml">com .html</a>
<a href="test">sem .html</a>

<script type="text/javascript">
    onmousemove = function adfy() {
        adfy_id = '.html'; //replace with your ID
        links = document.getElementsByClassName("addHtml");
        for (var i = 0; i < links.length; i++) {
            var hrefer = links[i].href;
            if (hrefer.match(".html") || hrefer.match("javascript:") || hrefer.match("#")) {
                links[i].href = links[i].href;
            } else {
                links[i].href = links[i].href + adfy_id;
            }
        }
    }

</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.