模拟CSS选择器程序
程序员文章站
2024-03-17 15:25:58
...
点击浏览器元素,弹出该元素的id、class或元素名
function cssSelector(element){
var parents=[];
var classes=[];
var ids=[];
var string=[];
var finalString = "html body";
parents.push(element.nodeName);
classes.push(element.className);
ids.push(element.id);
while(element.parentNode.nodeName != "#document" && element.parentNode.nodeName != "HTML" && element.parentNode.nodeName != "BODY"){
parents.push(element.parentNode.nodeName);
classes.push(element.parentNode.className);
ids.push(element.parentNode.id);
element = element.parentNode;
}
for(var i = parents.length-1;i > -1;i--){
string[i] = ids[i] ? ("#"+ids[i]) : (classes[i] ? ("."+classes[i]) : parents[i]);
finalString += (" " + string[i]);
}
if(finalString == "html body HTML"){
finalString = "html";
}
alert(finalString);
}
document.onclick = function(e){
cssSelector(e.target);
};