2013-01-18 49 views
1

也许这不能做,但万一我失去了一些东西:可能修改jQuery id选择器?

是否有可能临时修改jQuery的id选择(“#”),以便于操作说...一个DocumentFragment的,或从DOM中删除而不是默认行为的元素?

的原因,我问的是,我试图优化一些遗留代码重利用ID选择,以执行一些繁重工作DOM操作。但是,所有这些ID都属于单一元素。我看,如果该元素是从DOM删除,操控,然后重新插回的表现会更好。哪些不能做,因为所有那些“#”选择的...

(旁注:性能显着通过设置显示改善:操作前无,但仍然缓慢)。

+0

没有...只有元素可以通过'getElementById'找到。不过,您始终可以使用其他遍历方法。 –

+1

选择器只能从DOM中选择。你想要做的就是将这些片段存储为JavaScript变量。 – Blazemonger

+0

你可以通过将单一的祖先元素作为背景限制你的选择的搜索。 – jbabey

回答

1

你可以做,如果你存储被删除的元素在一个变量的引用:本文档中

// Get a div by id 
var div = $('#thediv'); 
// Remove it from the DOM 
div.remove(); 
// Change the color of the text inside it to red 
// Notice we're selecting with the div as the context 
$('p', div).css('color', 'red'); 
// Re-add div to DOM; text will be red 
document.body.appendChild(div[0]); 

http://codepen.io/anon/pen/sglIk