最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get parentNode tagName - Stack Overflow

programmeradmin2浏览0评论

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%';
        }
    });
}

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%';
        }
    });
}
Share Improve this question edited May 21, 2013 at 13:32 user1106925 asked May 21, 2013 at 13:19 Constantine GolubConstantine Golub 3517 silver badges22 bronze badges 2
  • But where in your code are you trying to read parentNode.tagName ?? – techfoobar Commented May 21, 2013 at 13:21
  • How are we supposed to help you without the associated HTML ? I would suggest making a fiddle... – Laurent S. Commented May 21, 2013 at 13:21
Add a ment  | 

1 Answer 1

Reset to default 3

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 acplish 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%';
            }
        });
    })
发布评论

评论列表(0)

  1. 暂无评论