user1820858
user1820858

Reputation: 55

Why is my JavaScript if statement not working?

The first if statement is not working although I passed the value of the block parameter as physicalActivityBlock:

function obj(select,block,idName) {
    var a=document.getElementById(select).value;
    var b=document.getElementById(block);
    var i=0;
    b.innerHTML = '';

   if(block=='physicalActivityBlock'){
       b.appendChild('<p>hello</p>');
   }
}

Upvotes: -1

Views: 68

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

The if condition looks fine, but the code in the if block is wrong. appendChild doesn't accept a string. It accepts a DOM node.

As you're using innerHTML anyway, you could do this:

if (block == 'physicalActivityBlock') {
    b.innerHTML = '<p>hello</p>';
}

I'd probably change the logic slightly so you only set innerHTML once:

function obj(select,block,idName) {
    var a=document.getElementById(select).value;
    var b=document.getElementById(block);
    var i=0;

   b.innerHTML = block=='physicalActivityBlock' ? '<p>hello</p>' : '';
}

If you really want to use appendChild, you'll have to create the element:

var p = document.createElement('p');
p.innerHTML = 'hello';
b.appendChild(p);

Upvotes: 3

Related Questions