Como posso obter o selector do objecto jQuery
$("*").click(function(){
$(this); // how can I get selector from $(this) ?
});
Existe uma maneira fácil de obter o selector de $(this)
? Existe uma forma de seleccionar um elemento pelo seu selector, mas Que tal obter o selector do elemento ?
18 answers
Ok, então em um comentário acima da pergunta asker Fidilip
disse que o que ele / ela está realmente atrás é obter o caminho para o elemento atual.
Aqui está um programa que irá "subir" a árvore DOM ancestral e, em seguida, construir um selector bastante específico, incluindo quaisquer atributos id
ou class
no item clicado.
Veja-o trabalhando em jsFiddle: http://jsfiddle.net/Jkj2n/209/
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function() {
$("*").on("click", function(e) {
e.preventDefault();
var selector = $(this)
.parents()
.map(function() { return this.tagName; })
.get()
.reverse()
.concat([this.nodeName])
.join(">");
var id = $(this).attr("id");
if (id) {
selector += "#"+ id;
}
var classNames = $(this).attr("class");
if (classNames) {
selector += "." + $.trim(classNames).replace(/\s/gi, ".");
}
alert(selector);
});
});
</script>
</head>
<body>
<h1><span>I love</span> jQuery</h1>
<div>
<p>It's the <strong>BEST THING</strong> ever</p>
<button id="myButton">Button test</button>
</div>
<ul>
<li>Item one
<ul>
<li id="sub2" >Sub one</li>
<li id="sub2" class="subitem otherclass">Sub two</li>
</ul>
</li>
</ul>
</body>
</html>
Por exemplo, se carregar no item da lista aninhada da 2ª lista no HTML abaixo, obteria o seguinte resultado:
HTML>BODY>UL>LI>UL>LI#sub2.subitem.otherclass
::aviso:
.o selector foi desacreditado a partir da versão 1.7, removido a partir de 1.9
O objecto jQuery tem uma propriedade do selector que vi ontem, quando cavei o seu código. Não sei se está definido nos documentos como é confiável (para a revisão futura). Mas funciona!
$('*').selector // returns *
Editar : Se você encontrar o selector dentro do evento, essa informação deverá, idealmente, fazer parte do evento em si e não do elemento, porque um elemento poderá ter vários eventos do 'click' atribuídos através de vários selectores. Uma solução seria usar uma embalagem para bind()
, click()
etc. para adicionar eventos em vez de adicioná-lo diretamente.
jQuery.fn.addEvent = function(type, handler) {
this.bind(type, {'selector': this.selector}, handler);
};
O selector está a ser passado como propriedade de um objecto chamado selector
. Acesse como event.data.selector
.
<p class='info'>some text and <a>a link</a></p>
$('p a').addEvent('click', function(event) {
alert(event.data.selector); // p a
});
Disclaimer: lembre-se que tal como acontece com live()
Eventos, a propriedade do selector pode ser inválida se DOM são utilizados métodos transversais.
<div><a>a link</a></div>
O código abaixo não vai funcionar, pois live
depende da propriedade do selector
o que neste caso é a.parent()
- um selector inválido.
$('a').parent().live(function() { alert('something'); });
O nosso método addEvent
vai disparar, mas tu também vais ver o selector errado - a.parent()
.
Em colaboração com @drzaus, criamos o seguinte plugin jQuery.
JQuery.getSelector!(function ($, undefined) {
/// adapted http://jsfiddle.net/drzaus/Hgjfh/5/
var get_selector = function (element) {
var pieces = [];
for (; element && element.tagName !== undefined; element = element.parentNode) {
if (element.className) {
var classes = element.className.split(' ');
for (var i in classes) {
if (classes.hasOwnProperty(i) && classes[i]) {
pieces.unshift(classes[i]);
pieces.unshift('.');
}
}
}
if (element.id && !/\s/.test(element.id)) {
pieces.unshift(element.id);
pieces.unshift('#');
}
pieces.unshift(element.tagName);
pieces.unshift(' > ');
}
return pieces.slice(1).join('');
};
$.fn.getSelector = function (only_one) {
if (true === only_one) {
return get_selector(this[0]);
} else {
return $.map(this, function (el) {
return get_selector(el);
});
}
};
})(window.jQuery);
Javascript Minificado
// http://stackoverflow.com/questions/2420970/how-can-i-get-selector-from-jquery-object/15623322#15623322
!function(e,t){var n=function(e){var n=[];for(;e&&e.tagName!==t;e=e.parentNode){if(e.className){var r=e.className.split(" ");for(var i in r){if(r.hasOwnProperty(i)&&r[i]){n.unshift(r[i]);n.unshift(".")}}}if(e.id&&!/\s/.test(e.id)){n.unshift(e.id);n.unshift("#")}n.unshift(e.tagName);n.unshift(" > ")}return n.slice(1).join("")};e.fn.getSelector=function(t){if(true===t){return n(this[0])}else{return e.map(this,function(e){return n(e)})}}}(window.jQuery)
Uso e Gotchas
<html>
<head>...</head>
<body>
<div id="sidebar">
<ul>
<li>
<a href="/" id="home">Home</a>
</li>
</ul>
</div>
<div id="main">
<h1 id="title">Welcome</h1>
</div>
<script type="text/javascript">
// Simple use case
$('#main').getSelector(); // => 'HTML > BODY > DIV#main'
// If there are multiple matches then an array will be returned
$('body > div').getSelector(); // => ['HTML > BODY > DIV#main', 'HTML > BODY > DIV#sidebar']
// Passing true to the method will cause it to return the selector for the first match
$('body > div').getSelector(true); // => 'HTML > BODY > DIV#main'
</script>
</body>
</html>
Ensaios de Fiddle w/ QUnit
$("*").click(function(){
$(this).attr("id");
});
Libertei um 'plugin' de jQuery: O selector de jQuery, pode obter um selector como este.
$("*").on("click", function(){
alert($(this).getSelector().join("\n"));
return false;
});
Tenta isto:
$("*").click(function(event){
console.log($(event.handleObj.selector));
});
Se sim, faça isto..
$("*").click(function(){
alert($(this)[0].nodeName);
});
Você não pode realmente obter o "selector", o" selector " no seu caso é *
.
Http://www.selectorgadget.com/ é um favorito concebido explicitamente para este caso de uso.
Dito isto, concordo com a maioria das outras pessoas em que você mesmo deve aprender os seletores de CSS, tentar gerá-los com código não é sustentável. :)Isto vai voltar imediatamente se houver uma identificação no elemento. Também adicionei uma verificação de atributos de nome e um selector de nth-child no caso de um elemento não ter id, classe ou nome.
O nome pode precisar de scoping no caso de haver vários formulários na página e ter entradas semelhantes, mas eu ainda não lidei com isso.
function getSelector(el){
var $el = $(el);
var id = $el.attr("id");
if (id) { //"should" only be one of these if theres an ID
return "#"+ id;
}
var selector = $el.parents()
.map(function() { return this.tagName; })
.get().reverse().join(" ");
if (selector) {
selector += " "+ $el[0].nodeName;
}
var classNames = $el.attr("class");
if (classNames) {
selector += "." + $.trim(classNames).replace(/\s/gi, ".");
}
var name = $el.attr('name');
if (name) {
selector += "[name='" + name + "']";
}
if (!name){
var index = $el.index();
if (index) {
index = index + 1;
selector += ":nth-child(" + index + ")";
}
}
return selector;
}
Eu estava a obter vários elementos mesmo depois das soluções acima, por isso estendi o trabalho dds1024, para um elemento dom ainda mais pontiagudo.
E. g. DIV:nth-child(1) DIV:nth-child(3) DIV:nth-child(1) ARTIGO:nth-child(1) DIV:nth-child(1) DIV:nth-child(8) DIV:nth-child(2) DIV:nth-child(1) DIV:nth-child(2) DIV:nth-child(1) H4:nth-child(2)
Código:
function getSelector(el)
{
var $el = jQuery(el);
var selector = $el.parents(":not(html,body)")
.map(function() {
var i = jQuery(this).index();
i_str = '';
if (typeof i != 'undefined')
{
i = i + 1;
i_str += ":nth-child(" + i + ")";
}
return this.tagName + i_str;
})
.get().reverse().join(" ");
if (selector) {
selector += " "+ $el[0].nodeName;
}
var index = $el.index();
if (typeof index != 'undefined') {
index = index + 1;
selector += ":nth-child(" + index + ")";
}
return selector;
}
Isto permite-lhe seleccionar a localização do elemento HTML clicado -
$("*").on("click", function() {
let selectorPath = $(this).parents().map(function () {return this.tagName;}).get().reverse().join("->");
alert(selectorPath);
return false;
});
Código Javascript para o mesmo, no caso de alguém precisar, como eu precisava. Esta é apenas a tradução apenas da resposta selecionada acima.
<script type="text/javascript">
function getAllParents(element){
var a = element;
var els = [];
while (a && a.nodeName != "#document") {
els.unshift(a.nodeName);
a = a.parentNode;
}
return els.join(" ");
}
function getJquerySelector(element){
var selector = getAllParents(element);
/* if(selector){
selector += " " + element.nodeName;
} */
var id = element.getAttribute("id");
if(id){
selector += "#" + id;
}
var classNames = element.getAttribute("class");
if(classNames){
selector += "." + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, ".");
}
console.log(selector);
alert(selector);
return selector;
}
</script>
function getSelectorFromElement($el) {
if (!$el || !$el.length) {
return ;
}
function _getChildSelector(index) {
if (typeof index === 'undefined') {
return '';
}
index = index + 1;
return ':nth-child(' + index + ')';
}
function _getIdAndClassNames($el) {
var selector = '';
// attach id if exists
var elId = $el.attr('id');
if(elId){
selector += '#' + elId;
}
// attach class names if exists
var classNames = $el.attr('class');
if(classNames){
selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
}
return selector;
}
// get all parents siblings index and element's tag name,
// except html and body elements
var selector = $el.parents(':not(html,body)')
.map(function() {
var parentIndex = $(this).index();
return this.tagName + _getChildSelector(parentIndex);
})
.get()
.reverse()
.join(' ');
if (selector) {
// get node name from the element itself
selector += ' ' + $el[0].nodeName +
// get child selector from element ifself
_getChildSelector($el.index());
}
selector += _getIdAndClassNames($el);
return selector;
}
Talvez útil para criar um plugin jQuery?
Isto não lhe mostra a localização do DOM, mas irá mostrar uma representação de texto do que você vê no depurador eg chrome, ao ver um objecto.
$('.mybtn').click( function(event){
console.log("%s", this); // output: "button.mybtn"
});
Https://developer.chrome.com/devtools/docs/console-api#consolelogobject-object
Isto confere o id ou o nome da classe, e tenta dar o maior selector exacto possível.
jQuery.fn.getSelector = function() {
if ($(this).attr('id')) {
return '#' + $(this).attr('id');
}
if ($(this).prop("tagName").toLowerCase() == 'body') return 'body';
var myOwn = $(this).attr('class');
if (!myOwn) {
myOwn = '>' + $(this).prop("tagName");
} else {
myOwn = '.' + myOwn.split(' ').join('.');
}
return $(this).parent().getSelector() + ' ' + myOwn;
}
Basta adicionar uma camada sobre a função $ desta forma:
$ = (function(jQ) {
return (function() {
var fnc = jQ.apply(this,arguments);
fnc.selector = (arguments.length>0)?arguments[0]:null;
return fnc;
});
})($);
$("a").selectore irá retornar "a"mesmo em versões mais recentes jQuery.
Que tal:
var selector = "*"
$(selector).click(function() {
alert(selector);
});
Não acredito que o jQuery tenha guardado o texto do selector que foi usado. Afinal, como é que isso funcionaria se fizesses algo assim:
$("div").find("a").click(function() {
// what would expect the 'selector' to be here?
});
A melhor resposta seria
var selector = '#something';
$(selector).anything(function(){
console.log(selector);
});