0

I have a problem with simple thing. I want to add a element into html div tag using createElement Method. I have tried a lot of diferent ways but always getting the same result - nothing happens.

This is my code:

function changeReleaseDate() 
{
    var parentElement = document.getElementByClassName("container body-content");
	var existingElement = document.getElementByClassName("btn btn-default");
	var newInput = document.createElement("input");
    newInput.type = "text";
    newInput.className = "form-control";
	parentElement.insertBefore(newInput, existingElement);
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
	<script src="script.js"></script>
</head>
<body>
    <div class="container body-content">
	    <h2>Index</h2>
		<button id="btn" type="button" onclick="changeReleaseDate()" class="btn btn-default">Default</button>
		<hr />
        <footer>
            <p>&copy;My ASP.NET Application</p>
        </footer>
    </div>
</body>
</html>

I also tried to use appendChild but in this case input field was placed out of div.

1 Answer 1

1

The problem is that getElementByClassName should be getElementsByClassName.

This method returns a HTMLCollection, so to access the first element from this list you need to use bracket with index 0:

var parentElement = document.getElementsByClassName("container body-content")[0];
var existingElement = document.getElementsByClassName("btn btn-default")[0];

Demo: http://jsfiddle.net/jak4efau/

However it's more convenient in your case to use querySelector method:

var parentElement = document.querySelector(".container body-content");
var existingElement = document.querySelector(".btn.btn-default");

Also note, that you need to take care of the case when user clicks button multiple times, you probably don't want to append multiple input fields.

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

1 Comment

Specifically, getElementsByClassName returns a HTMLCollection, not a NodeList.

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.