How to Check if Document Contains an Element
Asked Answered
P

4

5

I'm trying to check if the DOM contains an element with ID = "htmlFileLink."

let element = document.createElement('a');
element.id = 'htmlFileLink';
document.body.insertAdjacentHTML( 'beforeend', element );

if( document.body.contains( document.getElementById('htmlFileLink') ) ) {
	alert ('yes');
}
else {
	alert ('no');
}

Why is it alerting "no" instead of "yes?"

Pankhurst answered 5/4, 2018 at 18:27 Comment(2)
Because there's no elements in the body. insertAdjacentHTML waits for a HTML string as an argument, not an element. Use appendChild to append new elements to existing elements.Softcover
OK, this is the answer I was looking for, appendChild(). Please post as an answer so I can accept it.Pankhurst
F
7

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

DEMO

let element = document.createElement('a');
element.id = 'htmlFileLink';
element.innerText = 'Test';
document.body.appendChild(element);

if (document.body.contains(document.getElementById('htmlFileLink'))) {
  alert('yes');
} else {
  alert('no');
}
Failsafe answered 5/4, 2018 at 18:58 Comment(0)
C
0

The second parameter of insertAdjacentHTML must be a HTML.

Example

document.body.insertAdjacentHTML('beforeend', '<a id="htmlFileLink">Ele</a>');

if (document.body.contains(document.getElementById('htmlFileLink'))) {
  console.log('yes');
} else {
  console.log('no');
}
Catlin answered 5/4, 2018 at 18:34 Comment(0)
P
0

According to the specification:

insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.

That means that the function always expects the second argument to be a valid string of HTML, not a DOM element.

Look at the below snippet to make sure:

document.body.insertAdjacentHTML('beforeend', '<a id="htmlFileLink"></a>');

if (document.body.contains(document.getElementById('htmlFileLink'))) {
  alert ('yes');
} else {
  alert ('no');
}
Phonologist answered 5/4, 2018 at 18:37 Comment(0)
P
0

instead of creating element try to do below its simple and easy.

enter code here

<script>

if(document.getElementById('htmlFileLink')) {
    alert ('yes');
}
else {
    alert ('no');
}
</script>
Precept answered 5/4, 2018 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.