从包含中查找替代选择器 [英] Finding alternate selectors from contains

查看:99
本文介绍了从包含中查找替代选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过contains选择器获得的元素列表. 假设我想知道如何在个人资料页面上访问一个人的名字.我可以用自己的名字测试自己的个人资料.

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.

无需遍历DOM并计算选择器,是否还有另一种方法可以获取(单个或列表)选择器以显示来自contains查询的每个元素?

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?

推荐答案

这是一种沿单个元素的父级移动并在遇到ID或主体时停止的方法.

Here's an approach that walks up the parents of a single element and stops if ID or body is encountered.

它将创建如下选择器:

#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

这篇关于从包含中查找替代选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆