一、方法说明
通过IDomObject元素,获取完整的CSS选择器,过滤HTML和BODY元素,自动将class、id添加到选择器上,优先添加class,无class再添加id。如:
a元素的完整的CSS选择器为:DIV#result H3.t A
二、方法实现
public string GetFullCssSelector(IDomObject dom){ string str = ""; while (dom != null && dom.NodeName != null) { string nodeName = dom.NodeName; if (!(new[] { "HTML", "BODY"}.Contains(nodeName))) //过滤HTML、BODY { if (dom.HasAttribute("class")) { string s = dom.Attributes["class"]; s = s.Replace(" ", " ").Replace(" ", " ").Replace(" ", " "); string[] strings = s.Split(' '); foreach (string str2 in strings) { nodeName += "." + str2; } } else if (dom.HasAttribute("id")) { nodeName += "#" + dom.Attributes["id"]; } str = nodeName + " " + str; } dom = dom.ParentNode; } return str.Trim();}
--版权信息--
转载请标明文章出处,谢谢!
文章作者:易几
--版权信息--