.width() giving error $(…)[0].width is not a function?

前端 未结 4 944
生来不讨喜
生来不讨喜 2021-01-19 05:01

I have a table, and I\'m trying to find the width of each td in the table. I\'ve tried all kinds of variations of: $(\"td\")[0].width(), but none of them work,

相关标签:
4条回答
  • 2021-01-19 05:38

    while you said I'm trying to find the width of each td in the table so you need to loop through tds by using .each() ..

    $('td').each(function(){
       alert($(this).width());
    });
    

    and to select specific td there are more ways

    by using :eq() selector

    $('td:eq(0)');   // index start from 0
    

    or .eq() in jquery

    $('td').eq(0)        // index start from 0
    

    or :nth-child() selector

    $('td:nth-child(1)');    // index start from 1
    
    0 讨论(0)
  • 2021-01-19 05:40

    $("td")[0] is a DOM element not a jquery object. Simply wrap it as jquery $($("td")[0]).width()

    You need to get width of each td so you could use something like

    $.each('td', function() {
        var currentTDWidth = $(this).width(); // more code here
    });
    
    0 讨论(0)
  • 2021-01-19 05:43
    $("td")[0]
    

    Is a DOM Level element and not a jQuery Object. and .width() is a jQuery method, so you literally can't use it on that. Do either of the following:

    $("td").eq(0).width(); // On a jQuery object
    $("td")[0].offsetWidth; // On a DOM Level Element.
    

    To fetch the width of all the elements use .each

    $('td').each(function(){
       alert($(this).width());
    });
    
    0 讨论(0)
  • 2021-01-19 05:45

    Use eq(0) instead of [0] to preserve the jQuery object that has the width() function.

    0 讨论(0)
提交回复
热议问题