Constantine Golub
Constantine Golub

Reputation: 351

Get parentNode tagName

I'cant get parentNode.tagName from this code and put some style to li tag.

// path to catalog images
var img = $('.catalog ul li > img');
for (i = 0; i < img.length; i++) {
    var pic_real_width;
    // Make in memory copy of image to avoid css issues
    $("<img/>").attr("src", $(img[i]).attr("src")).load(function () {
        pic_real_width = this.width;

        if (pic_real_width > 500) {
            // this part of code not work
            var imageParent = this.parenNode.tagName = 'li';
            imageParent.style.width = '50%';
        }
    });
}

Upvotes: 2

Views: 9167

Answers (1)

user1106925
user1106925

Reputation:

You have parenNode instead of parentNode, and you seem to be assigning to that property, which is read-only.

    // ---------------------v             v---assignment won't work
var imageParent = this.parentNode.tagName = 'li';

If you just wanted the parent, there's no reason to mess with the .tagName.

var imageParent = this.parentNode;
imageParent.style.width = '50%';

Also, I don't see where you're appending the new <img> to the DOM. If it's not appended, it won't have a parent.

Maybe you meant to get the parent of the original image. To do that, each load() handler will need to close over the current i or img. You can use .each() to accomplish this.

$('.catalog ul li > img')
    .each(function(i, img) {
        var pic_real_width;

        $("<img/>").attr("src", $(img).attr("src")).load(function () {
            pic_real_width = this.width;

            if (pic_real_width > 500) {
                var imageParent = img.parentNode;
                imageParent.style.width = '50%';
            }
        });
    })

Upvotes: 3

Related Questions