jQuery toArray() function vs pure javascript code example


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.


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


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

// invalid code


 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

    <li>ASP and PHP</li>
    <li>PHP and Perl</li>

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)) {


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
    return ret_elems;

Try the same demo with pure JavaScript code

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Professional looking single page website using Twitter Bootstrap

Next Post

Tutorial – Inserting text and image content using CSS

Related Posts