1

I'm trying to make a function by which I can know the clicked element is text node or not.

var isTextNode = function(target){
  return $(target).contents().filter(function(){
    return this.nodeType === 3;
  });
};

$(document).on('click',function(e){
  //console.log(e.target);
  if(isTextNode(e.target).length === 1){
    console.log('clicked');
  }
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>
  Lorem ipsum dolor sit amet    <!-- clicking here should log "clicked" -->
  <span class="pull-right">
  <i class="fa fa-twitter"></i>         <!-- clicking here should do nothing -->
  100                              <!-- clicking here should log "clicked" -->
  </span>
</h4>
<div>
  plain text                       <!-- clicking here should log "clicked" -->
</div>
<img src="" width="300" height="300" /> <!-- clicking here should do nothing -->

But, I couldn't produce the right code.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

1 Answers1

0

maybe something like

$(document).on('click',function(e){

    if($(e.target).text() != ""){
        console.log('clicked');
    }
    // prevent event bubbling down the DOM-tree
    return false;
});
john Smith
  • 17,409
  • 11
  • 76
  • 117