Marat
Marat

Reputation: 672

JS insertAdjacentHTML() is completely ignored

Breaking my head to understand why is insertAdjasentHTML has no effect on DOM:

console.log(target);
console.log(`${this.errorTemplate.replace('ERROR_MESSAGE', e.message)}`);
target.insertAdjacentHTML('afterend', `${this.errorTemplate.replace('ERROR_MESSAGE', e.message)}`);

Here's the console output:

<input class="form-control input-round is-invalid" type="text" name="login_form[email]" id="login_form_email">

<div class="invalid-feedback d-block">Please enter a valid email address</div>

So, just nothing happens. Nothing is inserted.

Upvotes: 2

Views: 317

Answers (2)

Marat
Marat

Reputation: 672

My bad. Everything worked perfectly. It's just that the upper function was ran on a batch of targets, and each time it destroyed all the previous insertions.

Upvotes: 1

EugenSunic
EugenSunic

Reputation: 13693

First of all make sure you errorTemplate is of type string not object, otherwise you'll get an error stating replace method does not exist on the object etc.

When inserting the adjacent it needs to be a string, so if you have a DOM element such as a paragraph which needs to be inserted as an adjacent then define it as a string completely.

The replace method is irrelevant here it just returns a new string hence ignore it for resolving your root issue.

Here is an example (assuming the target is the invalid email address node element):

const target = document.querySelector('.invalid-feedback')
// should be a string
const errorTemplate = '<p>ERROR_MESSAGE</p>';
target.insertAdjacentHTML('afterend', errorTemplate.replace('ERROR_MESSAGE', 'NEW ERROR MESSAGE'));
<input class="form-control input-round is-invalid" type="text" name="login_form[email]" id="login_form_email">
<div class="invalid-feedback d-block">Please enter a valid email address</div>

Likewise, please go through the official docs for more clarification:

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Upvotes: 0

Related Questions