Obtener elemento en el que se hizo clic en JQuery

I'm using the following code to get the selected text, my question is, how can I get the element where the text was selected? I have 100 rows and 10 columns and I want to get the td and tr object and I want to check weather the text was selected inside the table.

function getSelectedText() {
  var t = '';
    t = window.getSelection();
  }else if(document.getSelection){
    t = document.getSelection();
  }else if(document.selection){
    t = document.selection.createRange().text;
  return t;
$(document).bind("mouseup", putSelectedToInput);

function putSelectedToInput(){
  var st = getSelectedText();


preguntado el 27 de agosto de 11 a las 14:08

5 Respuestas

En lugar de atar mouseUp for document bind it for td elementos,

 var selectedTd=$(this);

Respondido 27 ago 11, 19:08

Jquery's .mouseUp is deprecated. Use .click instead. - Andrade

Tienes que comprobar event.target. Be aware that if you have one or more child elements in each table cell, you need to walk up the DOM tree from event.target until you reach a td element (or not, in which case the click was outside a cell).

Respondido 27 ago 11, 19:08

You can get the clicked element in the mouseup event by doing this:

function putSelectedToInput(event){ // notice the event parameter

    var $clickedElement = $(event.target);

The clicked element may be any element inside the td. You can get the td itself with this:

// returns the closest parent that is a td (or the element itself if it's a td)
var $theTd = $clickedElement.closest('td');

Vea event.target y .closest ()

Respondido 27 ago 11, 19:08

Simplemente use:

elem = window.event.srcElement

Now the td or tr element which was clicked in is stored in the global variable called elem. Note that this would return every element in which the user has clicked, so you would have to check if it was a td or tr element, like so:

if(elem.tagName.toLowerCase() == "td" || elem.tagName.toLowerCase() == "tr")

Respondido 27 ago 11, 19:08

Respondido 27 ago 11, 18:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.