[英]jQuery detect already rendered element?
I need write some function which will be detect any jquery selector: already exists in DOM or not. 我需要编写一些函数来检测任何jquery选择器:DOM中是否已经存在。 How i can do that.
我该怎么做。
If element rendered it must return true, if element not rendered it must return false. 如果呈现元素,则必须返回true,如果未呈现元素,则必须返回false。
Possible selectors: 可能的选择器:
'<div />' // text jquery selected will converted to $('<div />')
$('<div />') // simple jquery selector such as jQuery('<div />')
'#somediv' or .somediv // already rendered DOM element
isDomExists('<div />')
=> false isDomExists('<div />')
=> isDomExists('<div />')
isDomExists($('<div />'))
=> false isDomExists($('<div />'))
=> isDomExists($('<div />'))
isDomExists($('#somediv'))
=> true isDomExists($('#somediv'))
=>是
This will return true for elements that are currently in the document, and selectors which match elements in the document. 对于文档中当前存在的元素以及与文档中的元素匹配的选择器,它将返回true。
function isInDoc(sel) {
var $sel = jQuery(sel);
return $sel.length && jQuery.contains(document.documentElement, $sel[0]);
}
You can also check the number of parents of the node, nodes with no parent is not contained in the DOM : 您还可以检查节点的父节点数,DOM中不包含没有父节点的节点:
http://jsfiddle.net/w6XZZ/ http://jsfiddle.net/w6XZZ/
HTML: HTML:
<div id="mydiv"></div>
Javascript : Javascript:
alert($("<div/>").parent().length);
alert($("#mydiv").parent().length);
$('<div />')
creates a new DIV element (but does not append to the DOM). $('<div />')
创建一个新的DIV元素(但不追加到DOM)。 What you need instead is $('div').length == 0
您需要的是
$('div').length == 0
您可以只使用jquerys .ready()
: 文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.