-3

I want to append a text within a class using Javascript, not by using jQuery. Example:

<div class="A">
    <div class ="B">
        <div class="C">
        </div>
    </div>
<div>

After putting text within Class="B", it should look like:

<div class="A">
    <div class ="B">
         This is text
        <div class="C">
        </div>
    </div>
<div>

I want to do it without using jQuery.

Thomas Orlita
  • 1,554
  • 14
  • 28
cyberoy
  • 363
  • 2
  • 7
  • 18

2 Answers2

0

Using insertAdjacentHTML() method:

var elements = document.getElementsByClassName("B"); // get all elements with class 'B'
for (var i = 0; i < elements.length; i++) { // for every element with class 'B':
    elements[i].insertAdjacentHTML("afterbegin", "This is text");
    // insert text just inside the element
}
<div class="A">
    <div class="B"><!-- Text will be inserted here -->
        <div class="C">
        </div>
    </div>
<div>
Thomas Orlita
  • 1,554
  • 14
  • 28
0

This will also do the trick:

function prependTextToClassB(){
        var textNode = document.createTextNode('This is text');
        var elB = document.querySelector('.B');
        var elC = document.querySelector('.C');
        elB.insertBefore(textNode, elC);
    }
Orr Siloni
  • 1,268
  • 10
  • 21