最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery detect already rendered element? - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question edited Aug 5, 2017 at 9:41 Cœur 38.8k25 gold badges206 silver badges278 bronze badges asked Nov 14, 2013 at 14:29 xercoolxercool 4,6397 gold badges29 silver badges33 bronze badges 4
  • 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
Add a ment  | 

4 Answers 4

Reset to default 3

This 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

发布评论

评论列表(0)

  1. 暂无评论