0

I have some class name fawas that displays some content. Actually i have to add some content below the Div in java script.please help me.

<div class="fawas">
    this is my name fawas khan.
</div>

my javascript code is

var dynamic = "this is my contact number."; var _body = document.getElementsByTagName('body') [0].innerHTML =dynamic;

what i'm getting is only a appended div.

Joe Doyle
  • 6,363
  • 3
  • 42
  • 45

4 Answers4

2

In pure javaScript, getting an element by className is ugly. See How to Get Element By Class in JavaScript? for more information.

Basically, you'll want this function:

function getElementsByClass(tagType, className) {
    var elems = document.getElementsByTagName(tagType);
    var returns = [];
    for (var i in elems) {
        if ((' ' + elems[i].className + ' ').indexOf(' ' + className + ' ') > -1) {
            returns.push(elems[i]);
        }
    }
    return returns;
}

Once you have that, the rest is not too bad:

var dynamic = document.createElement("div");
dynamic.innerHTML = "this is my contact number.";

var elements = getElementsByClass("div", "fawas");
if (elements.length > 0) {
    // just change the first, as you did in your post
    elements[0].parentNode.insertBefore(dynamic, elements[0].nextSibling);
}

I dynamically create your new div, rather than just a text string.

Then, I get the parent of the element you want to insert after, use the insertBefore function on whatever is after the element of your choice.

Here is a working fiddle.

As others have shown you, this can be a lot cleaner using jQuery. I don't know enough node.js to know if it has functions that will be more convenient, so I gave a pure JS solution.

Community
  • 1
  • 1
Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
1

In case you're interested in jQuery solution, here's a Fiddle

<div class="fawas">
  this is my name fawas khan.
</div>


$(function(){
  var dynamic = ('this is my contact number.');
  $('.fawas').after('<div class="fawas2">'+dynamic+'</div>');
});
Milan and Friends
  • 5,560
  • 1
  • 20
  • 28
0

Your html should be,

<div class="fawas">
    this is my name fawas khan.
</div>
<div id="fawas-2">
</div>

Your script should be,

<script type="text/javascript">
var dynamic = "this is my contact number."; 
document.getElementById('fawas-2').innerHTML =dynamic;
</script>
gvm
  • 1,153
  • 3
  • 12
  • 19
0

You can do this

var oldcontent = document.getElementsByTagName('body') [0].innerHTML;

document.getElementsByTagName('body') [0].innerHTML = oldcontent + dynamic

Where dynamic is the content you want to add

Shivam Shah
  • 524
  • 5
  • 10