0

I have create the dynamic div and now trying to change the inner html of it but its not working please help me here is the code

function like(id)
{
var orgnldiv=document.getElementById(id);
var ndiv=document.createElement('DIV');
ndiv.id = 'like';
ndiv.className="likeclass";
var classname = document.getElementsByClassName("likeclass");
orgnldiv.appendChild(ndiv); 
classname.innerHTML="example";
//alert(id);
 }

2 Answers2

3

Beware of the s in Elements. That means that you are getting a list rather than a single control.

Check How to use getElementsByClassName in javascript-function?

Community
  • 1
  • 1
Ted
  • 3,985
  • 1
  • 20
  • 33
  • yes i know about s in elements i want to change inner html of all the dive's which have same class –  May 09 '14 at 17:02
  • You need a loop do go through all controls in the resulting list – Ted May 09 '14 at 17:04
  • 1
    @AyyanAlvi Ted gave link, where you can find explanation how to do this. Just try to open it and try something by yourself. – Sharikov Vladislav May 09 '14 at 17:04
1

Use this:

function like(id)
{
    var orgnldiv=document.getElementById(id);
    var ndiv=document.createElement('DIV');
    ndiv.id = 'like';
    ndiv.className="likeclass";
    orgnldiv.appendChild(ndiv); 
    var elements = document.getElementsByClassName("likeclass");
    for(var i = 0; i < elements.length; i++) {
        elements[i].innerHTML="example";
    }
}

You get error because getElementsByClassName returns array of elements, not one elements. So you have to work with result like with array. If 1 element return loop will fire only 1 time. If 0 elements it wouldn't fire.

Hope this will help.

Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87