jQuery: debugging elements in the console

When we create complex DOM structures with jQuery, it's vital to keep track of the inner structure of each element. We can actually log such structures to the console in order to analyze how the DOM has been constructed. To accomplish this task, we need to gather as much information as possible about our elements. Let's see how.

We can create the following plugin, log():

(function($) {


    $.fn.log = function() {
    
        var that = this;
        var selector = that.selector;
        var context = that.context;
        var element = that[0];
        var attrs = element.attributes;
        var name = element.tagName.toLowerCase();
        var contents = that.html();
        var logContent = '';
        
        
        return that.each(function() {
        
            
            logContent += '[name]: ' + name;
            logContent += ' [selector]: ' + selector;
            logContent += ' [context]: ' + context;
            logContent += ' [attributes]: ';
            
            if(attrs.length > 0) {
            
                for(var i = 0; i < attrs.length; i += 1) {
                
                  var attrName = attrs[i].name;
                  var attrValue = attrs[i].value;
                  
                  logContent +=  attrName + ': ' + attrValue + ' ';
                
                
                }
            
            
            } else {
            
                logContent += 'no attributes ';
            
            
            }
            
            logContent += ' [contents]: ' + contents;
            
            
            console.log(logContent);
        
        
        
        });
        
        
    
    
    
    };



})(jQuery);

This simple plugin logs to the JavaScript console the name of the element, its selector and context, its attributes (if any) plus its HTML contents. Let's see an example. Given the following DOM structure:

<ul id="test">
	<li id="a" class="a" title="a">A</li>
	<li>B</li>
	<li id="c" class="c">C</li>
</ul>

We can use this plugin as follows:

$(function() {

    $('li', '#test').each(function() {
  
        $(this).log();
  
    });


});

And we get the following output in the console:

Leave a Reply

Note: Only a member of this blog may post a comment.