开发者

How can you tell the difference between a generated and a selected element?

Is it possible, in either the jQuery API or the DOM, to check if an element exists on the page or not?

Consider these two variables:

var selected = $('span#mySpan');
var created = $('<span id="mySpan">Testing</span>');

Both will return a jQuery object containing a span element. Is there any way to tell that the first exists on the page, an开发者_如何学Cd the second one does not?


Try

$(created).parents("html").length

Here are some more ways to do the same:

$(document).find(created).length
$(created).parents(document).length

Or using the contains method that was built for this task. It only accepts DOM nodes, so we need to unwrap it from the jQuery object

$.contains(document, created.get(0))

A pure DOM way will be to use the Node.compareDocumentPosition method. In the above example,

// get the DOM node
var createdNode = created.get(0);
var position = document.compareDocumentPosition(createdNode);
var isNotInDocument = (position & Node.DOCUMENT_POSITION_DISCONNECTED) != 0;


The only way I can think of doing this, aside from some kind of an extension to the underlying DOM api is to grab a copy of the entire DOM tree and then do a comparison against it.

In your example, won't your second span have no parent? In valid HTML a span should always have a parent. Just rules like that, assuming valid HTML/XHTML, might be useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜