How to get colspan value

I tried different approaches to jQuery:

var num = $(this).attr('colspan').text();
var num = $(this).attr('colspan').val();
var num = $(this).('td[colspan]').val();
var num = $(this).('td[colspan]').text();
var num = $(this).('td[colspan]').attr('id');

and this is from W3Schools: var num = document.getElementById($(this)).colSpan;

Bad luck. This is either undefined or unsached TypeError in myconsole.log()


EDIT: I tried your suggestions and it still doesn't work. Here is the piece of code in context:

$('table td').on('mouseenter mouseleave', function(e){
    var th, index, id, td;
    if(e.type === 'mouseenter'){
        id = $(this).attr('id');
        td = $(this);
        var num = $(this).attr('colspan');
        console.log("td = "+td+" colspan = "+num);
        td.addClass('highlight');

var $table_body_scroll=$('table.body_scroll'),
            header_table=$( '<table aria-hidden="true" class="header_table"><thead><tr><td></td></tr></thead></table>' ),
            scroll_div='<div class="body_scroll"></div>';
        var $targetHeaderTable=$("table.header_table").eq(index);

        $('thead tr th').each(function() {
            console.log("th = "+$(this).text());
            console.log("id = "+id);
            if ($(this).text() == id)
            {
                var num = td.attr('colspan');
                //console.log("td = "+td+" colspan = "+num);
                $(this).addClass('highlight');
            }
        });

        index = $('td').index($(e.target));
        $(e.target).prevAll().addClass('highlight');

    }else{
        $('.highlight').removeClass('highlight');
    }
});

and my console log: td = [object Object] colspan = undefined

+3
source share
2 answers

Use propto get the value set for the attribute / property, this will reflect any changes made to the property using JS after the page loads:

$(this).prop("colSpan");

JS Fiddle: http://jsfiddle.net/9u8L2/1

+4
source

if thisrefers to td then

var span  = $(this).prop('colSpan')//or
var span  = $(this).attr('colspan')
0
source

All Articles