script only in one div

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>

To use this adfly coding for .html in the links on my site, there are more than 300 so I do not have to do it manually. It worked very well, but it is disrupting other links that do not need it.

I would like to know if it has only one div to work on?

    
asked by anonymous 08.08.2016 / 02:06

2 answers

1

Add an attribute of 'id' (with a name of course) to your div and use the document.getElementById method to capture it. So you will not have the links property on your element and you will have to use HTMLElement.prototype.getElementsByTagName to get the hyperlinks of div in an array.

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

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>
    
08.08.2016 / 14:26
0

Add to links that have .html a class, in this case I added .addHtml . So the function will only work on 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>
    
08.08.2016 / 10:12