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

82 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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!

0
On

It works ok and it's quite clear & straight-forrward. The only thing you could improve is adding a dot before each class :

$class = $this.prop('class') 
             ? '.'+$.trim($this.attr('class')).replace(/\s+/g,'.') 
             : '';

Here's a live demo: http://jsfiddle.net/cdWXN/1/