この関数を使用できます。基本的に要素を取り、逆方向に動作して正確なパスを確認します。あなたが計画しているものには使用しませんでしたが、なぜ機能しないのかわかりません。
function mirrorpath ( elm ) {
/// add an indentifying segment to the path for each parent element
var addtopath = function( elm ){
var node = $(elm), ident = '';
/// first off, add our nodeName to our identity
ident += node.get(0).nodeName;
/// if we have an id, then we are specific enough
if ( node.attr('id') ) {
ident += '#' + node.attr('id');
}
/// otherwise
else{
/// if we have a class, that's good :)
if ( node.attr('class') ) {
ident += '.' + node.attr('class').split(' ').join('.');
}
/// now make it more accurate with an index offset
ident += ':eq('+node.prevAll(ident).add(node).index(node)+')';
}
/// add our new path segment
path.push( ident );
}
/// step through the target elements parents and build our path
var parents = $(elm).parents().get(), path = [], i = parents.length;
while ( i-- ) { addtopath( parents[i] ); }; addtopath( elm );
/// implode the path and return
return path.join(' ');
}
返されたパスは、メイン ページと iframe の両方で要素を評価して見つける必要があります。パスを jQuery に戻すだけです。私はあなたの質問がかなり奇妙な要求であることを告白しなければなりません;)
ps。非常に複雑で深い要素でこのコードをテストしていないため、失敗する特定の状況が発生する可能性があります...パスストレージに配列を使用しないことで最適化される可能性もあります(そして、反復ごとに愚かにも再結合します... この問題を最適化するためにコードを更新したばかりですが、jQuery と Sizzle のおかげで、これまで必要としていたすべての機能が機能しました。
編集/更新
これが役に立つ場合に備えて、コードを少し修正して、jQuery プラグインに変換することにしました。現在、実際の css パスの生成に関していくつかの最適化が実施されており、jQuery によって解析されたときにパスがどのように処理されるかについて最適化されています。
(function($){
$.fn.cssPath = function () {
var paths = [], addtopath = function( elm ){
if ( elm && (elm.nodeName || (elm instanceof $ && elm.length)) ) {
var node = $(elm), ident = String(node.get(0).nodeName).toLowerCase();
/// if we have an id, then we are specific enough
if ( node.attr('id') ) {
ident += '#' + node.attr('id');
}
/// otherwise
else{
/// if we have a class, that's good :)
if ( node.attr('class') ) {
ident += '.' + node.attr('class').split(' ').join('.');
};
/// make sure there is a point to being more specific (leads to nicer paths)
if ( node.siblings(ident).length > 0 ) {
/// now make it more accurate with an index offset
//ident += ':eq('+node.prevAll(ident).add(node).index(node)+')';
ident += ':nth-child('+(node.index()+1)+')';
};
};
/// add our new path segment
return ident;
};
};
this.each(function(){
/// find the parents for this element, and add the current element to the list
var parents = $(this).parents().get(), path = '', i = parents.unshift(this) && parents.length;
/// build up the path string per parent
while ( i-- ) { path += (path ? ' > ' : '') + addtopath( parents[i] ); };
/// return the path to our paths list
paths.push(path);
});
/// if one path, return string, if more return array
return ( paths.length > 1 ? paths : paths[0] );
}
})((typeof jQuery != undefined) && jQuery);
使用法:
var path = $('#my_target_element').cssPath();
出力例:
html > body > div#BlogArchive1 > ul.hierarchy > li.archivedate.expanded > a