How can I rewrite this without using the jQuery library with just JavaScript?

I have a few lines of code in jQuery:

     var central = $('#townid option:contains("Central")');
     if (central.length){
        central.insertAfter('select option:first-child');
     }

How can I rewrite it without using the jQuery library with JavaScript only?

+3
source share
1 answer

A correct translation would be something like this:

var selects = document.getElementsByTagName('select'),
    options = document.getElementById('townid').getElementsByTagName('option'),
    options = Array.prototype.slice.call(options), //2 lines only for readability
    tmp = document.createDocumentFragment();

for(var i = 0, l = options.length; i < l; i++) {
    var option = options[i],
        text = option.innerText || option.textContent;
    if(text.indexOf('Central') > -1) {
        tmp.appendChild(option);
    }
}

for(var i = 0, l = selects.length; i < l; i++) {
    var select = selects[i],
         opts = select.getElementsByTagName('option');
    if(opts.length > 1) {
        select.insertBefore(tmp.cloneNode(true), opts[1]);
    }
    else {
        select.appendChild(tmp.cloneNode(true));
    }
}

Demo

Depending on the markup (and optimized depending on the browser (for example, support querySelectorAll)) this can be simplified. ) For instance. if you know that there will always be only one parameter that contains "Central" and whether there is only one element selector not.

select, (.. > 1) , Central. :

var options = document.getElementById('townid').getElementsByTagName('option');

for (var i = 0, l = options.length; i < l; i++) {
    var option = options[i],
        text = option.innerText || option.textContent;
    if (text.indexOf('Central') > -1) {
        if (i > 1) {
            option.parentNode.insertBefore(option, options[1]);
        }
        break;
    }
}

DEMO

Update:

Central, :

if(text === 'Central')
+6

All Articles