2

I have input form like this:

<form>
    <label for="name">Name :</label>
    <input type="text" id="name">
</form>

I want to add span tag with Javascript using this code:

var inputName = document.getElementById('name');
var h = document.createElement("span");
var t = document.createTextNode("Hello World");
h.appendChild(t);
inputName.appendChild(h);

But it seem it doesn't work as i expected. this is the result that i get:

<form>
    <label for="name">Name :</label>
    <input type="text" id="name">
        <span>Hellow World</span>
    <input>
</form>

So how do i can do that properly? and if you would be kind to tell me how can i remove that span later. thanks.

4
  • Although there are of course cases where you want to add and remove elements. it's often simpler to just put the element int he DOM (HTML) to start with, then turn it on and off with CSS classes. Commented Jan 20, 2017 at 2:54
  • @torazaburo don't you think it wouldn't effective if we have different error messages on 1 input? such "input can't be empty", "input need more than 2 character"? Commented Jan 20, 2017 at 3:19
  • In that case, I would have an error element in the original DOM (HTML) which is hidden or shown depending on whether or not there is an error, then populate it with different text values using errorElement.textContent = errorMessage. Commented Jan 20, 2017 at 3:21
  • @torazaburo thanks for the suggestion, i will give it try later to see which one is suit for my case. thanks. Commented Jan 20, 2017 at 6:15

1 Answer 1

2

you need to use .after for adding new element after the element and for removing this element you can use nextElementSibling.remove();

var inputName = document.getElementById('name');
var h = document.createElement("span");
var t = document.createTextNode("Hello World");
h.appendChild(t);
inputName.after(h);

function remove(){
  
  inputName.nextElementSibling.remove();
  
}
<form>
    <label for="name">Name :</label>
    <input type="text" id="name">
</form>

<button onClick="remove()">Remove</button>

Sign up to request clarification or add additional context in comments.

2 Comments

@torazaburo you right, i try to google where is .after in javascript, but google is give me a jQuery. it strange, i don' use jQuery but Deep code is correct and i don't have any problem with it.
@torazaburo , Henra yes this is strange that there is no documentation for this , i found ChildNode.after documentation but not for element.after(). However this works n firefox and chrome perfectly. Could be a non documented feature perhaps ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.