0

Is there a way to create a new div within an existing div using JavaScript?

I'd like the following to happen:

  1. Create a new div with class="three" and put it inside div class="one".
  2. Create a new div with class="text" and put it inside class="three" and add the text 'this is sample text'.

The end result should look like this:

enter image description here

.two{
  width:700px;
  height: 600px;
  background-color: yellow;
}

.three{
  width:300px;
  height: 200px;
  transform: translate(50%, -250%);
  background-color: red;
}
.text{
  text-align: right;
  transform: translate(-5%, 440%);
  color: black;
}
<div class="one">
  <div class="two">
  </div>
</div>

2 Answers 2

1

// get a reference to the first div by using its class as search path
var divOne = document.querySelector('.one');
// create a new element
var divThree= document.createElement('DIV');
// add a class 'three' to a newly created element
divThree.classList.add('three');
// and add a newly created element to divOne
divOne.appendChild(divThree);

// now create a div for text, set its class to 'text' and append it to divThree
var txt = document.createElement('DIV');
txt.classList.add('text');
txt.innerHTML = 'this is sample text';
divThree.appendChild(txt);
.two{
  width:700px;
  height: 600px;
  background-color: yellow;
}

.three{
  width:300px;
  height: 200px;
  transform: translate(50%, -250%);
  background-color: red;
}
.text{
  text-align: right;
  transform: translate(-5%, 440%);
  color: black;
}
<div class="one">
  <div class="two">
  </div>
</div>

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

1 Comment

If it's just text you can also use txt.innerText
0

Using jquery you can write the below code.

$(document).ready(function(){
    $(".one").html("<div class='three'><div class='text'>This is a sample text</div><div>");
});

Comments

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.