Search code examples
jqueryparents

Is there a better way to get the names of all parent elements?


To get the names of all parent elements?

 $(document).on('click', function(e){
    var parents = $(e.target).parents().map(function(){ 
        var $this = $(this),
            $id = $this.prop('id') ? '#'+$this.attr('id') : '',
            $class = $this.prop('class') ? '.'+$this.attr('class') : ''; 
        return this.tagName.toLowerCase()+$id+$class;
        }).get().join(" < ");
    prompt('The path to the element, Luke:',parents);
 });

FIDDLE with example.

EDIT: Nice! Thanks, guys! Updated FIDDLE.


Solution

  • It works well, I've run some tests and none got to improve your current method.

    Additionally to the suggestion provided by gion_13, I would suggest reversing the order of displaying the elements!

    Depending on your goal, it might have a better readability from HTML to clicked element, by using .reverse():

    $(document).on('click', function(e){
      var parents = $(e.target).parents().map(function(){
    
        var $this  = $(this),
            $id    = $this.prop('id') ? '#'+$this.attr('id') : '',
            $class = $this.prop('class') 
                       ? '.'+$.trim($this.attr('class')).replace(/\s+/g,'.') 
                       : '';
    
        return this.tagName.toLowerCase()+$id+$class;
    
      }).get().reverse().join(" > ");
    
      prompt('The path to the element, Luke:',parents);
    });
    

    The Fiddle example here!