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.
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>
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);
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;
Related
In which format should i enter IMG SRC to a Result in Javascript?
var result = document.getElementById('test');
result.innerHTML = price + "img src='catcoin.png'";
I'd suggest avoiding assigning to innerHTML generally unless it's the only decent option. You can append a new img element to a container like this:
result.appendChild(document.createElement('img')).src = 'catcoin.png';
document.getElementById('test').src = "catcoin.png";
var el = document.querySelector("#test")
var img = document.createElement("img");
img.setAttribute('src', 'catcoin.png');
el.appendChild(img)
Hey so don't use text to add elements in JavaScript.
var elem = document.createElement("img");
elem.src = 'test.png';
Then append this new image element to result:
document.getElementById("test").appendChild(elem);
With plain js:
var price = '$ 04.89';
var test = document.getElementById('test');
while (test.firstChild) {/* optional cleanup, faster than test.innerHTML = '' */
test.removeChild(test.firstChild);
}
test.appendChild(document.createTextNode(price));
test.appendChild(document.createElement('img')).src = 'caticon.png';
<div id='test'></div>
function JGallery() {
this.elements = this._init();
this.overlay = this.elements.overlay;
this.media_hld = this.elements.media_hld;
}
JGallery.prototype._init = function(){
var overlay = document.createElement('div');
var media_hld = document.createElement('div');
return{
'overlay': overlay,
'media_hld': media_hld
}
};
This is where I create a document fragment and using it so I can add several div to same element:
JGallery.prototype.getReference = function(holder) {
var overlay = this.overlay;
var media_hld = this.media_hld;
var that = this;
var holderChildren = holder.querySelectorAll('img');
var docfrag = document.createDocumentFragment();
holderChildren.forEach(function (e) {
e.addEventListener('click', JGallery.prototype.showMe.bind(that), false);
var media_holder = that.media_hld;
media_holder.textContent = "<img src="+e.getAttribute('src')+">";
docfrag.appendChild(media_holder);
//it only appends the last child of my array...
});
overlay.appendChild(docfrag);
};
my goal is to have something like this:
<div class="JGallery_BG">
<div class="JGallery_mediaContainer"><img src="images/thumb_video.jpg"></div>
<div class="JGallery_mediaContainer"><img src="images/thumb_video.jpg"></div>
</div>
by the way the forEach function works well, 8 or 9 times. But I'm not sure whether it adds node to docFrag on every run or not.
Another thing, I'm not insisting to use a document fragment, if there is a better way to add multiple elements to one element, I like to know about it and use it.
One of the problems is that you are constantly re-using the same media holder <div> element in every iterations.
In the code below that.media_hld is always referencing the same element.
var media_holder = that.media_hld;
media_holder.textContent = "<img src="+e.getAttribute('src')+">";
docfrag.appendChild(media_holder);
If you clone the node it should work and you also need to set the innerHTML property, not the textContent.
var media_holder = that.media_hld.cloneNode();
One other thing I did spot is that what's returned from querySelectorAll is not an array and thus doesn't have a forEach method.
You could borrow forEach from an array instance though:
[].forEach.call(holderChildren, forEachBodyFunction);
The entire thing could read:
JGallery.prototype.getReference = function(holder) {
var docfrag = document.createDocumentFragment(),
images = holder.querySelectorAll('img');
[].forEach.call(images, function (img) {
img.addEventListener('click', JGallery.prototype.showMe.bind(this), false);
var media_holder = this.media_hld.cloneNode();
media_holder.appendChild(img.cloneNode());
docfrag.appendChild(media_holder);
}.bind(this));
this.overlay.appendChild(docfrag);
};
I need create a div above another div, but I dont have access to the css file, thus everything needs to be done via JavaScript.
This is my wrong code:
var div = document.getElementById("down");
var divAbove = document.createElement("div");
divAbove.id = "up";
divAbove.style.background = "red";
divAbove.style.position = "absolute";
divAbove.style.width = "150px"
div.appendChild(divAbove );
I can't see the new div.
If you can pinpoint the container element you can make use of .insertBefore()
More Info (docs)
var container = document.getElementById("container");
var div = document.getElementById("down");
var divAbove = document.createElement("div");
divAbove.id = "up";
divAbove.style.backgroundColor = "red";
divAbove.style.width = "110px"
divAbove.style.height = "60px"
divAbove.innerHTML = "Added via JS"
container.insertBefore(divAbove, div);
<div id='container'>
<div id='down' style='height: 60px; width: 110px; background-color: yellow'>
Existing element
</div>
</div>
This work.
var div = document.getElementById("down");
var divAbove=document.createElement("div");
divAbove.id = "up";
divAbove.style.background = "red";
divAbove.style.position = "absolute";
divAbove.style.width = "150px";
divAbove.style.height= "150px";
div.appendChild(divAbove);
From this point I would say that the div is there, but due to a typo in divAbov.style.background = "red"; it does not have a visible background. Try fixing the typo.
If the problem persists, please post your console log if there is any errors in there.
The reason you can't see new div is that you didn't give any body to it. For example, it may be a case to write before appending divAbove the following:
divAbove.innerHTML = "Hello World";
I am retrieving some information from an xml file ( movie information ) and I am creating dynamically some DOM elements according to each movie. I want, when I click on the test element, to get the value of the title of the movie. Right now, no matter which movie I click, it gets the title of the last movie that was introduced.
How can I get the title of each individual movie when I click on that div and not the last one introduced by the for-loop?
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("movie");
for (i=0;i<x.length;i++)
{
var titlu = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var description = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var descriere = document.createElement('div');
descriere.className='expandedDescriere';
descriere.innerHTML = description;
var titlediv = document.createElement('div');
titlediv.className = 'title';
titlediv.id='title';
titlediv.innerHTML = title;
var test=document.createElement('div');
test.className='test';
test.onclick= function(){
var filmName= test.previousSibling.innerHTML;
alert(filmName);
}
placeholder.appendChild(titlediv);
placeholder.appendChild(test);
placeholder.appendChild(descriere);
}
I think your problem might be in the function you assigned to onclick:
test.onclick= function(){
var filmName= test.previousSibling.innerHTML; // <===
alert(filmName);
}
the marked line should be var filmName= this.previousSibling.innerHTML;
My guess is that the var test is hoisted out of the for loop, meaning that when the loop finished, all the onclick function are referencing the same test variable which is the last element you created.
Use this to reference the clicked element:
test.onclick = function() {
var filmName = this.previousSibling.innerHTML;
alert(filmName);
};
I have a link that is attached with an "onclick" function. When pressed it attaches an img element into a separate div called "mediaBox". The problem I'm having is that if it's pressed multiple times then it attaches more instances of the img. How can I control this. I'm still new to JavaScript and I prefer to receive this answer in pure Javascript not jQuery, as I will cross that bridge after I have a full understanding of Javascript.
var rkf = document.getElementById("submenulinks").getElementsByTagName("li")[0];
rkf.onclick = function(){
var client = document.getElementById('client');
var description2 = document.getElementById('description2');
var role = document.getElementById('role');
var mediaBox = document.getElementById('mediaBox');
var thumb = document.getElementById("thumb");
var client2 = document.getElementById("client2");
var newImage = document.createElement("img");
client2.innerHTML = "Role - Applications";
client.innerHTML = "RKF Real Estate";
client2.innerHTML = "Role - Applications";
description2.innerHTML = "Quarterly Catalog of Exclusive Listings managed by RKF";
role.innerHTML = "Custom designed Cover and listings content. Tables were also utilized within Indesign. <br><br><b><i> Photoshop and Indesign</i></b>";
newImage.setAttribute("src", "../images/rkf_cover.jpg");
newImage.setAttribute("height", "500px");
newImage.setAttribute("width", "387px");
newImage.setAttribute("alt", "rkf");
newImage.setAttribute("href", "#");
mediaBox.style.backgroundImage = "none";
document.getElementById("mediaBox").appendChild(newImage);
newImage.style.display = "block";
newImage.style.marginLeft = "auto";
newImage.style.marginRight = "auto";
newImage.style.marginTop = "25px";
}
rkf.onclick = function(){
var client = document.getElementById('client');
...
...
...
// Remove the handler after it ran once.
this.onclick = null; // <<<<<========================
}
Since you do want to use jQuery in the future, it's equal to:
$('#submenulinks li:first').one('click', handler);