Anikin Skywalker
Anikin Skywalker

Reputation: 35

JS DOM createElements and appendChild not working

I am trying to create a website with information of some students. Hence I need to create dynamic profile cards and append them to body. But DOM always gets me.

function student(src, name) {
    this.src = src;
    this.name = name;
}

var student1 = student(1, "ABC");

var card = document.createElement('div');
card.className = 'card';

var image = document.createElement('img');
image.src = 'images\/students\/' + student1.src + '.jpg';
card.appendChild(image);

var stuName = document.createElement('p');
stuName.className = 'name';
var stuNameText = document.createTextNode(student1.name);
stuName.appendChild(stuNameText);
card.appendChild(stuName);

However nothing is showing up on the screen. placeHere is the id of body. Any help will be appreciated.

Edit:
Apparently applying all necessary changes and moving my script tag to body helps.

Upvotes: 0

Views: 1348

Answers (3)

Jadli
Jadli

Reputation: 860

the way you creating Student1 Object is wrong var student1 = new student(1, "ABC"); you forget new keywork

function student(src, name) {
    this.src = src;
    this.name = name;
}

var student1 = new  student(1, "ABC");

var card = document.createElement('div');
card.className = 'card';

var image = document.createElement('img');
image.src = 'images\/students\/' + student1.src + '.jpg';
card.appendChild(image);

var stuName = document.createElement('p');
stuName.className = 'name';
var stuNameText = document.createTextNode(student1.name);
stuName.appendChild(stuNameText);
card.appendChild(stuName);
var main=document.getElementById('main')
main.appendChild(card)
.card{    color: palevioletred;
    background: yellow;}
<div id="main"></div>

Upvotes: 1

Umair Arshad
Umair Arshad

Reputation: 61

You didn't append your code to any DOM element, create new div in body and append your code into that div. <div id="stdCard"></div> and then you can use innerHTML to append card into parent div created. document.getElementById("stdCard").innerHTML = card;

Upvotes: 1

Mr Khan
Mr Khan

Reputation: 2292

You have to append all these newly created elements to a div already in the DOM or body tag will work too. Currently, the elements you created are not attached to DOM. So lets say you have a div

<div id="mydiv"></div>

you can append to that div you newly created elements like this:

ley mydiv = document.getElementById('mydiv');
mydiv.appendChild(card);

or you can append it to the body itself like so:

ley body= document.getElementByTagName('body');
body.appendChild(card);

Upvotes: 1

Related Questions