通过ID删除HTML元素 [英] Removing HTML Element by Id

查看:451
本文介绍了通过ID删除HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码从DOM树中删除元素:

I am using the following code to remove an element from the DOM tree:

 function onItemDeleted(name) {

           $("#" + name).remove();                       

       }

这会降低性能,因为我没有指出该元素的任何父级.该元素是包含在TABLE元素中的TR.此元素的DOM搜索将从顶部开始,可能是BODY.所以会是这样的:

Would this be bad for performance since I am not indicating any parent for the element. The element is a TR contained in a TABLE element. The DOM search for this element will start at the top which might be BODY. So would it be something like this:

正文=> DIV =>表格=> TR(找到)

BODY => DIV => TABLE => TR (found)

如果我找到TR的父级(即TABLE),则搜索将如下所示:

If I find the parent of TR which is TABLE would the search be like this:

TABLE-> TR

TABLE -> TR

我不知道上面的说法是否正确,因为我认为搜索将始终从根节点开始.

I don't know if above will be true since I think search will always start at the root node.

推荐答案

jQuery对ID搜索进行了优化.因此,$("#" + name)实际上与$(document.getElementById(name))相同.从来源,第120(1.4)行:

jQuery optimises for ID searches. So, $("#" + name) is effectively the same as $(document.getElementById(name)). From the source, line 120 (1.4):

// HANDLE: $("#id")
} else {
    elem = document.getElementById( match[2] );

这篇关于通过ID删除HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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