My jquery is not adding div to correct node - javascript

var out = [];
out.push('<div class="newData">');
for (var i = 0; i < 5; i++) {
out.push('<img src="' + data.data[i].images.low_resolution.url + '"/>');
count++;
// if (data.pagination.next_url = "") flag++;
if (count > 4) {
myurl = data.pagination.next_url;
count = 0;
}
out.push('</div>');
$('#wrap').append(out);
I have this simple code but in inspect elements it shows.
<div id="wrap">
<div class="newdata"></div>
<img scr='"asd"/>
<img scr='"asd"/>
<img scr='"asd"/>
</div>
Why is is immediately closing the newdata div and why not putting photos in it?

Try using a string ,don't forget to close the for loop
var out = '';
out+='<div class="newData">';
for (var i = 0; i < 5; i++) {
out+='<img src="' + data.data[i].images.low_resolution.url + '"/>';
count++;
// if (data.pagination.next_url = "") flag++;
if (count > 4) {
myurl = data.pagination.next_url;
count = 0;
}
}
out+='</div>';
$('#wrap').append(out);

You have the div '<div class="newData">' start outside the for loop and you close it inside the for loop. Then you add it inside the loop. Make sure you add valid html when you append it to #wrap, then it will work.
Edit: Additionally as others have pointed out: use strings to add the strings to each other and then append.

The issue is because you can only append whole elements to the DOM. When you append the opening div tag, the browser will automatically close it for you. This means your img elements are then created as siblings.
You could instead change your logic to create the div container, then build the HTML string in a loop and append that together. Try this:
var $div = $('<div class="newData"></div>').appendTo('#wrap');
var html = '';
for (var i = 0; i < 5; i++) {
html += '<img src="' + data.data[i].images.low_resolution.url + '"/>');
}
$div.append(html);

You are not closing the loop, that causing you the problem
out+='</div>';
$('#wrap').append(out);
add this in last of your loop

Related

Returning html code in javascript

I want to print html code in Javascript code.
I want to open and close the bottom line of five li tags. How can I do this with a for loop
jQuery(document).ready(function () {
InsertLi();
});
function InsertLi(){
var count = 5;
for (var i = 0; i < count; i++) {
var codeBlock = ' <li>' + i + '</li>';
$(".bildirimMetin").html(codeBlock);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>
You need to use append function instead. html function every time overrides your html content with the new content and you get only the last one. Also create your string with 5 li-s and then call the append at the end to work with DOM one time and have more performance.
function InsertLi() {
var count = 5;
var codeBlock = '';
for (var i = 0; i < count; i++) {
codeBlock += ' <li>' + i + '</li>';
}
$(".bildirimMetin").append(codeBlock);
}
jQuery(document).ready(function () {
InsertLi();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin"></ul>
If you have only one item with bildirimMetin class, it will be better to use id instead of class.
Well, another solution, close to your code, with html, store all strings in your variable via += then you must define your variable before for loop also move your html after it. Your current code not working because it just store last string not all.
InsertLi();
function InsertLi() {
var count = 5;
var codeBlock = '';
for (var i = 0; i < count; i++) {
codeBlock += '<li>' + i + '</li>';
}
$(".bildirimMetin").html(codeBlock);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>
you had a couple issues. One was overwriting the inner HTML instead of appending. The other was a syntax issue.
function InsertLi(){
var count = 5;
for (var i = 0; i < count; i++) {
var codeBlock = ' <li>' + i + '</li>';
$(".bildirimMetin").append(codeBlock);
}
}
jQuery(document).ready(function () {
InsertLi();
}
);

Sort divs (added dynamically) by classname

I have been struggling to find a way in which I could sort Divs after being displayed .So far, I have used prepend() and append() and I have managed to show at first the players that are streaming, but the next divs are random. I want to be able to show who's online, who's not and who has closed the account in order.
I have already tried deferred method: $.when(makeDivs()).then(sortDivs());
but it's not working properly, any idea how I can fix this?
My codepen: http://codepen.io/diegomdzr/pen/vKWGbd
I don't have the reputation to comment yet. But from my understanding, you want to make the classNames of divs in alphabetical order after they have been applied to the document?
function reOrder() {
var div = document.getElementsByTagName('div');
var cn = []; //ClassNames of each div.
for (var i = 0; i < div.length; i++) {
cn.push(div[i].className);
}
cn = cn.sort(); //sort the array in alphabetical order.
var oDiv = [];
for (var i = 0; i < cn.length; i++) {
//for each array item in cn, find where it's element is, remove the element, continue.
for (var ii = 0; ii < div.length; ii++) {
if (div[ii].className == cn[i]) {
oDiv.push(div[ii]);
var newDiv = [];
for (var iii = 0; iii < div.length; iii++) {
//Remove the element from the array.
if (div[iii] != div[ii]) {
newDiv.push(div[iii]);
}
}
div = newDiv;
}
}
}
return oDiv;
};
reOrder();
This will return an array of the elements, but sorted. You can then replace all of the elements of the document with these sorted elements.
Sorting is expensive, should be avoided if possible, and isn't a particularly good solution here.
It's way simpler to create a container (div) for each of your streamer categories, (online|offlie|nonExistent) then simply append HTML, as it is generated, to the appropriate container.
$(document).ready(function() {
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "comster404", "brunofin", "HorussTV"];
var link = "https://twitch.com/";
// Create/append containers here (or hard-code them in HTML) ... in correct order of presentation within #streamers.
var $onlineStreamers = $("<div/>").appendTo($('#streamers'));
var $offlineStreamers = $("<div/>").appendTo($('#streamers'));
var $nonExistantStreamers = $("<div/>").appendTo($('#streamers'));
streamers.forEach(function getStatus(element) {
$.getJSON("https://api.twitch.tv/kraken/channels/" + element + "?callback=?", function(json) {
var img = json.logo || "http://res.cloudinary.com/djnwhbm1z/image/upload/v1468187598/unknown_i7m43p.png";
$.getJSON("https://api.twitch.tv/kraken/streams/" + element + "?callback=?", function(json) {
// Append HTML to the appropriate container
if(json.stream) {
$onlineStreamers.append('<div class="online"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span><b>Game:</b></br>' + json.stream.game + ' </br><b>Status: </b>' + json.stream.channel.status + '</span></div></div>');
} else if(json.status == 422) {
$nonExistantStreamers.append('<div class="nonExistant"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span>Account Closed</span></div></div>');
} else {
$offlineStreamers.append('<div class="offline"><h4>' + element + '</h4><img src="' + img + '" class="profPic"><div class="content text-center"><span>Offline</span></div></div>');
}
});
});
});
});
Notes:
No sorting required unless the entries need to be sorted within each category.
You can probably purge class="online" etc from the appended HTML, unless those classes are used elsewhere.

Writing HTML for a string of values using javascript and jquery?

I want to have my page's html to appear as:
<div class='container'>
<div class='domain-list0'>Hello</div>
<div class='domain-list1'>World</div>
</div>
Here is my html and js: Pen from Codepen.io
Instead of creating the first "domain-list" and then creating another one for the next, it is just overwriting the previous "domain-list". This is why it shows the last string value. Anyone know how to fix this?
Thanks!
You are using .html() which removes the existing content, and replaces it with the new content. You need to use append so that the new content is added after the last child.
var myStringArray = ["Hello", "World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
var $el = $("<div />", {
'class': 'domain-list' + i,
html: "<p>" + myStringArray[i] + "</p>"
}).appendTo("div.container");
// $el refer to the newl added element
}
Demo: Fiddle
use .appendTo() so that it will return the newly created element which can be used for further processing
for (var i = 0; i < arrayLength; i++) {
$("div.container").html("<div class='domain-list'></div>");
$(".domain-list:nth-child("+i+")").html("<p>"+myStringArray[i]+"</p>");
//Do something
}
Try to use appendTo in jquery
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
$("<div class='domain-list"+i+"'></div>").html("<p>"+myStringArray[i]+"</p>").appendTo("div.container");
//Do something
}

Changing current attribute of HTML,from where the function gets called

I am using JavaScript to build a dynamic HTML page, here is my code:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append("<img src=\"" + getImage(images[i])+" \"width=\"90\"");
}
The getImage function returns an image...My question, how can I with JavaScript or Jquery in each iteration change the attribute of that current line, for example changing width or any image attribute of that current line in my getImage function . If I use $('this') it returns the object, but not in reference to that current line. Can I change those things in every iteration inside that function? so as a result I would get:
<img src="1.jpg" width="20">
<img src="2.jpg" width="90" >
function getImage(i) {
// some code
// WANT TO CHANGE HERE THE IMG ATTRIBUTE OF <img src "" width="">
return image ;
}
The idea of course is to change many more attributes...
If you want to be able to change the image attributes from within getImage then you should not use string-concatenation to build the image-tag.
Try something like:
for (var i = 0; i < images.length; i++) {
$("#a1").append(getImage(images[i]));
}
with:
function getImage(input) {
var $img = $('<img>').attr({
src: '%your-source%', // maybe from input?!
width: 100
});
// do other stuff with $img as needed
return $img;
}
You can't do that as you have it now. As far as I understand, getImage simply returns an URL to an image. And it can't modify width of img tag. You can do it like that:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append("<img src=\"" + getImage(images[i]) + " \"width=\"" + images[i].width + "\"");
}
assuming that your images array contains objects with fields src and width
Or you should make your getImage return whole img tag HTML:
for (var i = 0; i < getImage.length; i++) {
$("#a1").append(getImage(images[i]));
}
function getImage(index) {
// some code
return "<img src=\"" + image + " \"width=\"" + width + "\"";
}
This may have some mistakes but i just want to share an idea of how you could do this in another way.
for (var i = 0; i < getImage.length; i++) {
$("#a1").append(getImage(images[i]));
}
function getImage(i) {
var s = // get the src
var w = // width based on i
return "<img src=\"" + s+ " \"width=\"" + w+ "\"" ;
}

Client side javascript, creation of several elements and show each asap

Client side javascript code creates some elements (about 50-100) in a cycle:
for (var i = 0; i < list.length; i++) {
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
mainObj.appendChild(obj);
}
There are some problems with browser rendering. For example, IE just freezes until it finishes the cycle, and then shows all elements at once. Is there a way to show each created element separately and immediately after appendChild()?
This is due to the single threaded nature of browsers. Rendering will not begin until the thread becomes idle. In this case, it's when your loop has completed and the function exits. The only way around this is to (sort of) simulate multiple threads using timers, like so:
var timer,
i = 0,
max = list.length;
timer = window.setInterval(function ()
{
if (i < max)
{
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
mainObj.appendChild(obj);
i++;
}
else
window.clearInterval(timer);
}, 1);
The obvious drawback is that this will take your loop longer to complete because it's fitting the rendering inbetween each iteration.
insert a delay between adding successive entries, with setTimeout().
function insertEntry(list, ix) {
if (ix == null) {
ix = 0;
}
else if (ix < list.length) {
var elt= document.createElement("DIV");
var attr = document.createAttribute('id');
attr.value = 'item'+ix;
elt.setAttributeNode(attr);
elt.innerHTML = "<span class='itemCls'>" + list[ix].Id + ': ' + list[ix].Name +
"</span><!-- some more simple code -->\n";
mainObj.appendChild(elt);
ix++;
}
if (ix < list.length) {
setTimeout(function(){insertEntry(list, ix);}, 20);
}
}
Kick it off with:
insertEntry(myList);
where myList is like this:
var myList = [
{ Id : '1938377', Name : 'Sven'},
{ Id : '1398737', Name : 'Walt'},
{ Id : '9137387', Name : 'Edie'}
...
};
demo: http://jsbin.com/ehogo/4
I wold do it like this using jQuery instead:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
timer = window.setInterval(function ()
{
for (var i = 0; i < 100; i++) {
$('#container').append('<div>testing</div><br />');
}
},10);
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
jQuery does it so quickly, you won't even need to bother about showing as they are created, but you can make it smoother by adding a timer as the example shows.
Is there a specific reason you want the DOM to be updated after every cycle?
It would be alot faster if you create all the elements in one javascript element, and add this one element to the DOM when the cycle is finished.
var holder = document.createElement("DIV");
for (var i = 0; i < list.Length; i++) {
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
holder.appendChild(obj);
}
mainObj.appendChild(holder);

Categories

Resources