Uncaught TypeError: undefined is not a function javascript function

I wrote the "bubble sort" function to sort a list of images. I can't understand why the function returns the "Uncaught TypeError: undefined is not a function". Can anyone help me?

$j(document).ready(function() { 
    var list = $j("dt").find("a").find("img");

    bubbleSort(list, list.size());    

function bubbleSort(a, size)
    do {
        var swapped = false;
        for (var i = 0; i < size - 1; i++) {
            var img = getAlt(a, i);
            var img2 = getAlt(a, i + 1);

            if (img > img2) {
                var temp = a[i].attr('src');
                a[i].attr('src') = a[i + 1].attr('src');
                a[i + 1].attr('src') = temp;
                swapped = true;
    } while (swapped); // <----- line error

function getAlt(list, pos) {
    var img = list[pos].attr("alt");
    img = img.split(' ');
    return img[3];



Instead of list[pos] use list.eq(pos) since with the first one you get a raw HTML element (which has no attr function) and the second way you get a jQuery object (which has an attr function)

Also use list.length instead of list.size() since the size function has been deprecated since version 1.8

Finally as noted by M. Page

a[i].attr('src') = a[i + 1].attr('src');

should be

a.eq(i).attr('src', a.eq(i + 1).attr('src'));

and the same goes for statements like it

You should also consider altering your getAlt function in the event that the img does not have an alt attribute

function getAlt(list, pos) {
    var img = list.eq(pos).attr("alt") || "";    
    if(img) {
        img = img.split(' ');
    return img[3] || "";

All of these changes can be found in the following fiddle http://jsfiddle.net/ejhq03qy/1/

a[i].attr('src') = a[i+1].attr('src');

has to be written:

a[i].attr('src', a[i+1].attr('src'));

Same for line below.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.