Domanda

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]. This is the problem, I don't know how to do that.

GetElementByID seems to don't work with element created by dynamically.

Any help? Thanks.

È stato utile?

Soluzione 2

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.

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/

Altri suggerimenti

You can use document.contains to check if a element is in the 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

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


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. This way you can apply any css styles to it.

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.

As @slowpython said I'd rather create a DOM element with ID or NAME.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top