Over a million developers have joined DZone.

Query String Aware JavaScript

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

As developers we know it's useful to read the query string (everything after the '?' in the URL) to allow for customisations.

However, I didn't think I could read the query string in the script tag from within the JavaScript - until now.

The Trick

The trick is simple, in your externally loaded script, you read the last DOM element loaded (this script tag that loaded the current script), grab the last DOM element, read the src and there's your query string.

The Code

// script included using test.js?a=10&z=50
function getLastChild(el) {
return (el.lastChild && el.lastChild.nodeName != '#text') ? getLastChild(el.lastChild) : el;

var query = getLastChild(document.lastChild).getAttribute('src').replace(/.*\?/, '');

The query variable now contains the full query string and can be used to change the result of your script.

I would then pass that in to my getQuery function so I had access to it as an object.


I've created two separate snippets on JS Bin (my new weekend project), one containing the external script code (with getQuery) and one that makes the call:

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Remy Sharp, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}