Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a couple of 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 JQuery library just with JavaScript?

like image 528
kamaci Avatar asked Mar 22 '26 16:03

kamaci


1 Answers

A correct translation would be something like:

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

This could be simplified a lot depending on the markup (and optimized depending on the browser (e.g. support for querySelectorAll)). E.g. if you know that there will always only be one option that contains "Central" and whether there exists only one select element or not.

Here is a stripped down version for one select element, known size of the list (i.e. > 1) and only one option that contains Central. So basically just reordering the option:

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:

If the option's text should be exactly Central, compare the text normally:

if(text === 'Central')
like image 122
Felix Kling Avatar answered Mar 25 '26 04:03

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!