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.

4 Answers 4

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.

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

1 Comment

Great answer, in pure JS and then a note about jQuery being an option.
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>');
});

Comments

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>

Comments

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

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.