问题
I have a list of elements obtained through the contains
selector.
Let's say I want to know how to access a person's name on a profile page. I can test my own profile with my own name.
let name = $(':contains(jamie)');
I'd like to store a selector based on the above results that could be used to retrieve the name from any profile.
Without walking the DOM and calculating a selector, is there another way to get a (single or list) selector to each element that comes out of the contains
query?
回答1:
Here's an approach that walks up the parents of a single element and stops if ID or body is encountered.
It will create selectors like:
#test > div:eq(0) > ul:eq(0) > li:eq(2)
JS
var $el = $('li:contains(3)');
var selectors=[];
selectors.push(getSelector($el));
$el.parents().each(function(){
var $node = $(this);
selectors.push(getSelector($node));
if($node.is('body') || $node[0].id ){
return false
}
});
var selector = selectors.reverse().join(' > ');
console.log(selector);
/* test selector in DOM */
$(selector).css('color','red')
function getSelector($el){
var id = $el[0].id;
if(id){
return '#' +id;
}
if($el.is('body')){
return 'body';
}
return $el[0].tagName.toLowerCase() +':eq(' + $el.index() +')';
}
With an extra loop it can be made to combine multiple elements with same selector format into a comma separated selector
DEMO
回答2:
Try adding a unique attribute to each prospective element; could then get , set element by filtering unique attribute value
$(function() {
var elem = "<span class=profile data-uuid=123>Jamie Dixon</span>"
$("body").append(elem);
// `let` name ..
var name = $.map($(":contains(Jamie Dixon)"), function(uuid, i) {
return $(uuid).data("uuid")
});
$("[data-uuid=" + name[0] + "]").css("color", "blue"); // do stuff
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
来源:https://stackoverflow.com/questions/28880926/finding-alternate-selectors-from-contains