Finding alternate selectors from contains

泄露秘密 提交于 2020-01-17 05:37:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!