简体   繁体   English

如何知道动态创建的元素是否存在?

[英]How to know if an element, created dynamically, exist?

I have this simple function: 我有这个简单的功能:

var x = document.createTextNode("ERROR");
document.body.appendChild(x);

So then I need to create an IF to verify if this message exist [If this message has been created]. 因此,我需要创建一个IF来验证此消息是否存在[如果已创建此消息]。 This is the problem, I don't know how to do that. 这是问题,我不知道该怎么做。

GetElementByID seems to don't work with element created by dynamically. GetElementByID似乎不适用于动态创建的元素。

Any help? 有什么帮助吗? Thanks. 谢谢。

You are creating a text node, not an element. 您正在创建文本节点,而不是元素。 You need to create an element and give it an id to be able to use getElementById . 您需要创建一个元素并为其指定一个ID,以便能够使用getElementById

I don't know of any reasonable way to search for a text node, although you could always check the text nodes of the element you attached it to and see if it's there. 我不知道有什么合理的方法来搜索文本节点,尽管您始终可以检查附加到该元素的元素的文本节点,然后查看它是否在那里。

var message = "ERROR";
var t = document.createTextNode(message);
var node = document.getElementById('content').appendChild(t);
if (document.getElementById('content').innerHTML !== message) {

  console.log('element not added');
} else {
  console.log('element added');
}

Here is a fiddle: 这是一个小提琴:

http://jsfiddle.net/btipling/rBg4w/ http://jsfiddle.net/btipling/rBg4w/

You can use document.contains to check if a element is in the DOM 您可以使用document.contains检查元素是否在DOM中

Just a quick example of how it works 只是一个简单的例子

document.contains($('<div>')[0]); // FALSE

And

document.contains($('<div>').appendTo('body')[0]); // TRUE

jQuery only used for a shorthand to element creation jQuery仅用于元素创建的简写

This also works for text nodes and you can use contains on any node. 这也适用于文本节点 ,您可以在任何节点上使用包含。

document.body.contains(Node); // Example

The browser support is somewhat very good 浏览器支持有些不错

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Node.contains 文档: https : //developer.mozilla.org/en-US/docs/Web/API/Node.contains


Question specifics: 问题细节:

var x = document.createTextNode("ERROR");
document.body.appendChild(x);
document.contains(x); // Should be TRUE

I believe this would work: 我相信这会起作用:

var x = document.createTextNode("ERROR");
var element = document.body.appendChild(x); //returns text node
if(!element){
    //element was not added
}

although if I were you I might create a span element with an id or a class called error. 尽管如果我是我,我可能会创建一个具有id或名为error的类的span元素。 This way you can apply any css styles to it. 这样,您可以对其应用任何CSS样式。

Try this: 尝试这个:

var x = document.createTextNode("ERROR");
document.body.appendChild(x);

if (document.body.innerText.indexOf('ERROR')>=0){
    alert('"ERROR" found');
}

indexOf doesn't work in all browsers. indexOf不适用于所有浏览器。

As @slowpython said I'd rather create a DOM element with ID or NAME. 正如@slowpython所说,我宁愿使用ID或NAME创建一个DOM元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM