jQuery toArray() function vs pure javascript code example

jquery_logo

jQuery toArray() method

toArray() method applies to matched jQuery DOM elements. It returns an array of these matched element objects.

Example :- Get array of all table row objects.

jQuery("tr").toArray()

It returns array of all <tr> objects, but not jQuery(“<tr>”) objects

['<tr>','<tr>','<tr>']

So, If you want to use any jQuery method each() over them, it won’t work.

// invalid code

jQuery("tr").toArray().each(function(){
  $(this).sort();
})

 Then, why to use jQuery toArray() method?

There are many JavaScript native functions not available to jQuery objects as methods, you could use toArray() to get plain object then apply native DOM methods over them.

Demo usage:- Highlight all list items start with string PHP

<ul>
    <li>JavaScript</li>
    <li>PHP</li>
    <li>ASP and PHP</li>
    <li>PHP and Perl</li>
    <li>Python</li>
</ul>

jQuery toArray() example

$(document).ready(function () {
    var list_elems_jq = $('li').toArray();
    for (i in list_elems_jq) {
        if (list_elems_jq[i].innerHTML.match(/^php/i)) {
            $(list_elems_jq[i]).css("background-color","#FF0");
        }
    }

Output

Here, String.match(/regex/) method doesn’t available in jQuery, so you could use it over native HTMLElement objects.

Alternative pure javascript function for jQuery toArray() method

function toArray(selector) {
    elems = document.querySelectorAll(selector);
    ret_elems = [];
    for (var i in elems) {
        if (elems[i].nodeType == 1) { // means nodeType = ELEMENT_NODE
            ret_elems.push(elems[i]);
        }
    }
    return ret_elems;
}

Try the same demo with pure JavaScript code

Total
0
Shares
Previous Post

Professional looking single page website using Twitter Bootstrap

Next Post

Tutorial – Inserting text and image content using CSS

Related Posts