SegFault
SegFault

Reputation: 1044

Javascript getting the number of elements in getElementsByClassName

I have the following javascript code:

b = document.getElementsByClassName('name1');
c = document.getElementsByClassName('name2');
if (b.length != 0) {
    document.getElementByTagName('body')[0].innerHTML = b[0].innerHTML 
else if (c.length != 0) {
    document.getElementByTagName('body')[0].innerHTML = c[0].innerHTML
}
else document.getElementByTagName('body')[0].innerHTML = 'error';

But I am not getting the desired rendering. The whole page renders even when divs with class name name1 and name2 are present.

What am I doing wrong?

Upvotes: 0

Views: 1524

Answers (2)

Taha Rehman Siddiqui
Taha Rehman Siddiqui

Reputation: 2533

You were using getElementByTagName instead of getElementsByTagName. Here is the updated script.

b = document.getElementsByClassName('name1');
c = document.getElementsByClassName('name2');
if (b.length != 0) {
    document.getElementsByTagName('body')[0].innerHTML = b[0].innerHTML;
else if (c.length != 0) {
    document.getElementsByTagName('body')[0].innerHTML = c[0].innerHTML;
    }
    else document.getElementsByTagName('body')[0].innerHTML = 'error';
}

Upvotes: 1

VisioN
VisioN

Reputation: 145388

  1. You skipped the closing } bracket in if statement;
  2. There is no getElementByTagName method in native JavaScript;
  3. You'd better use document.body instead.

Here is a bit more correct code:

var b = document.getElementsByClassName("name1"),
    c = document.getElementsByClassName("name2");

if (b.length > 0) {
    document.body.innerHTML = b[0].innerHTML;
} else if (c.length > 0) {
    document.body.innerHTML = c[0].innerHTML;
} else {
    document.body.innerHTML = "error";
}

Also, I wouldn't suggest you to change .innerHTML property, it is much efficient to use .appendChild() method instead, i.e.:

document.body.appendChild(document.createTextNode("error"));

Upvotes: 3

Related Questions