Skip to content Skip to sidebar Skip to footer

How Do I Set A Attribute To A Specific Element When Using A For Loop In Javascript?

Below I have a function assigned to a variable. Essentially I got it to work (apply a attribute to a collection of elements). My problem is I'd like the elements which will be set

Solution 1:

A few small logic tweaks are needed to do what you want. Like this:

varURLChecker = (functioniffe() {
  var publicAPI = {
        getURL: function() {
            for (var i = 0; i < arguments.length; i++) {
                return {
                    'smo': 'http://url.nyc.com',
                    'smodev': 'http://smodev.rye.foo.com',
                    'url1_sans_3w': 'http://url1.com',
                    'url2': 'http://www.url2.com',
                    'url3': 'http://www2.url3.com'
                }[arguments[i]];
            }
        },
        searchURL: function() {
            var link, url;
            for(var i = 0, len = arguments.length; i < len; i++) {
                url = this.getURL(arguments[i]);
                for (var j = 0, jlen = document.links.length; j < jlen; j++) {
                    link = document.links[j];
                    if (link.href.indexOf(url) !== -1) {
                        link.setAttribute("target", "_blank");
                    }
                }
            }
        }
    };
return publicAPI;
})();

URLChecker.searchURL('smo', 'smodev');

There were just a few issues with how you were checking the url and you needed to loop over both the url and the arguments.

There was also an issue with the indexOf that a parenthesis ended at the wrong position.

JS Fiddle here: https://jsfiddle.net/dkksgcc7/

Solution 2:

Couple things wrong, but they're easy to fix. First of all, URLChecker.searchURL accepts one parameter and you're passing it two. Change your function to work with for(var k in arguments) { ... } and check against publicAPI.getURL(arguments[k]) so that you can get all the urls checked. Secondly, when you check against links.href, it normalizes it. What that means is that you think you're checking "http://url.nyc.com" against your array item of "http://url.nyc.com", but in reality (at least in chrome) it changes your href to "http://url.nyc.com/" (note the added slash). Checking against links.getAttribute('href') will fix that. Lastly, your logic seems off. You're checking links.href.indexOf, but links.href isn't an array, you should just need if (links.getAttribute('href') === publicAPI.getURL(arguments[k])). Final result would be this:

varURLChecker = (functioniffe() {
  var publicAPI = {
    getURL: function() {
      for (var i = 0; i < arguments.length; i++) {
        return {
          'smo': 'http://url.nyc.com',
          'smodev': 'http://smodev.rye.foo.com',
          'url1_sans_3w': 'http://url1.com',
          'url2': 'http://www.url2.com',
          'url3': 'http://www2.url3.com'
        }[arguments[i]];
      }
    },
    searchURL: function() {
      for(var k inarguments) {
        for (var i = 0, l = document.links.length; i < l; i++) {
          var links = document.links[i];
          if (links.getAttribute('href') === publicAPI.getURL(arguments[k])) {
            document.links[i].setAttribute("target", "_blank");
          }
        }
      }
    }
  };
  return publicAPI;
})();
URLChecker.searchURL('smo', 'smodev');
a[target]:after {
  content: '\2197';
}
<ahref="http://url.nyc.com">http://url.nyc.com</a><br><ahref="http://smodev.rye.foo.com">http://smodev.rye.foo.com</a><br><ahref="http://url1.com">http://url1.com</a><br><ahref="http://www.url2.com">http://www.url2.com</a><br><ahref="http://www.url3.com">http://www.url3.com</a>

Solution 3:

One problem in your code is this line:

if (links.href.indexOf(publicAPI.getURL(url) !== -1)) {

You didn't balance your parentheses quite correctly. Change it to:

if (links.href.indexOf(publicAPI.getURL(url)) !== -1) {

There's a different problem that you didn't ask about yet, but might bite you later.

It looks like you're trying return an array of urls from getUrl, but you're actually only returning a single string: the result of the first match. If you actually want this to return an array, try this:

getURL: function() {
    var result = [];
    for (var i = 0; i < arguments.length; i++) {
        result.push({
            'smo': 'http://url.nyc.com',
            'smodev': 'http://smodev.rye.foo.com',
            'url1_sans_3w': 'http://url1.com',
            'url2': 'http://www.url2.com',
            'url3': 'http://www2.url3.com'
        }[arguments[i]]);
    }
    return result;
},

If you do this, though, you'll have to modify your link filter down below to match. It might look something like this:

if (links.href.indexOf(publicAPI.getURL(url)[0]) !== -1) {

If this isn't the case, and you just wanted to be able to pass a list of URLs to getURL and have it try to match one of them, then no changes are necessary here.

Solution 4:

I would try a small different approach to your publicAPI object, like this one:

var publicAPI = {
    getURL: function(url) {
          var targetUrls = {
                'smo': 'http://url.nyc.com',
                'smodev': 'http://smodev.rye.foo.com',
                'url1_sans_3w': 'http://url1.com',
                'url2': 'http://www.url2.com',
                'url3': 'http://www2.url3.com'
            };

         return targetUrls[url] ? targetUrls[url] : false;
    },

    searchURL: function() {
        var urls = arguments;

        for (var i = 0, l = document.links.length; i < l; i++) {
            var links = document.links[i];

            for (var j=0; j < urls.length; j++) {
                if (links.href.indexOf(publicAPI.getURL(urls[j])) !== -1) {
                    links.setAttribute("target", "_blank");
                }
            }

        }
    }
};

It is a bit clear to read, because you are explicitly passing the arguments needed to getURL function one by one instead of making it handle all the arguments that comes from another function.

Try to see if it works.

Post a Comment for "How Do I Set A Attribute To A Specific Element When Using A For Loop In Javascript?"