JS & Dom - Tips & Tricks #2
Mon Jan 09, 2017 · 339 words

Last year, David Walsh published an article called 7 Essential JavaScript Functions where he shared some JavaScript utility/helper snippets. One of the interesting techniques used in one of the functions is where he gets the absolute URL for a page. He does this using something like the following:

var getAbsoluteUrl = (function() {
  var a;
  return function(url) {
    if(!a) a = document.createElement('a');
    a.href = url;
    return a.href;
  };
})();

// Usage
getAbsoluteUrl('/something'); // https ://example.com/something

This example reveals a clever little technique. Basically, this function takes advantage of JavaScript’s ability to create elements that don’t actually exist in the DOM. From there, you can get info from that element as you please. In this case, the desired result is the full URL of the page. The browser automatically fills out full URLs in the href value of links, even if they’re written in relative format. So with this we can easily grab the full URL from just a relative page link.

Similarly, someone in the comments posted the following snippet:

function isValidEmail(string) {
  string = string||'';
  var lastseg = (string.split('@')[1]||'').split('.')[1]||'',
      input = document.createElement('input');
      input.type = 'email';

  input.required = true;
  input.value = string;
  return !!(string && (input.validity &&
                       input.validity.valid) && 
                       lastseg.length);
}

console.log(isValidEmail('')); // -> false
console.log(isValidEmail('asda')); // -> false
console.log(isValidEmail('asda@gmail')); // -> false
console.log(isValidEmail('asda@gmail.com')); // -> true

There’s a lot going on there, but the principle is the same. The script creates an email input field, without actually inserting it into the page, and then information is gleaned from the input. The acquired info falls in line with what the browser would do if the email input actually existed and was interacted with on the page. This is along the same lines as what happens with feature detection using a library like Modernizr.

So the basic lesson here is, if you want to find out info on how a browser handles certain HTML elements, remember that those elements don’t actually have to be in the DOM. You can create them yourself and then run some tests and respond accordingly.


back · he thought · he could · so he did · main