I need write some function which will be detect any jquery selector: already exists in DOM or not. How i can do that.
If element rendered it must return true, if element not rendered it must return 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 />'))
=> false
isDomExists($('#somediv'))
=> true
I need write some function which will be detect any jquery selector: already exists in DOM or not. How i can do that.
If element rendered it must return true, if element not rendered it must return 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 />'))
=> false
isDomExists($('#somediv'))
=> true
- if($(selector).length > 0){ // dom exists } – Gowsikan Commented Nov 14, 2013 at 14:32
- No, $('<div />').length returns 1. It's not correct! I need check element in DOM... – xercool Commented Nov 14, 2013 at 14:34
- If you're looking for a DIV just use $('div') – schlingel Commented Nov 14, 2013 at 14:37
- 1 Use $.contains – billyonecan Commented Nov 14, 2013 at 14:38
4 Answers
Reset to default 3This will return true for elements that are currently in the document, and selectors which match elements in the document.
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 :
http://jsfiddle/w6XZZ/
HTML:
<div id="mydiv"></div>
Javascript :
alert($("<div/>").parent().length);
alert($("#mydiv").parent().length);
$('<div />')
creates a new DIV element (but does not append to the DOM). What you need instead is $('div').length == 0
You could just use jquerys .ready()
:
Documentation