Returning html code in javascript - 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();
}
);

Related

How not to make <br> a tag

<script>
var y="<br>"
function repeater(num){
for (var i=0;i<num;i++)
{document.write(y) }
}
document.write(repeater(4))
</script>
My goal is to make the tag appear
4 times, not the actual breaks. The result shows undefined.
Since the question is asking for Javascript solution not JQuery (since no jQuery tags), I'll add the answer using Javascript.
<script>
var y = "<br>"
function repeater(num) {
for (var i=0; i < num; i++) {
document.body.innerText += y;
}
}
repeater(4);
</script>
or maybe you need to set a text into the spesific element (<div id="app"><div>)? no problem, we can improve the code a little bit.
<script>
var y = "<br>"
function repeater(el, num) {
for (var i=0; i < num; i++) {
el.innerText += y;
}
}
var el = document.getElementById('app');
repeater(el, 4);
</script>
<script>
var res = "";
var y="<br>";
function repeater(num){
for (var i=0;i<num;i++) {
res = res + y;
}
$('#customDiv').text(res);
}
(repeater(4))
You can put a custom <div id="customDiv"></div> inside your html file.

How do I create different button for each item in an array / JavaScript

Here's my code:
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
}
}
I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.
The best way is to append created buttons in container.Each by each
var never = [1,2,3,4,7];
function please () {
var more=document.getElementById("more");
for (var i = 0; i < never.length; i++) {
var butt=document.createElement("button");
butt.innerHTML=never[i];
more.appendChild(butt);
}
}
By appending to innerHTML instead of assigning, like
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
}
}
please();
<div id="more">
</div>

My jquery is not adding div to correct node

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

Append an Array to an Unordered List

What I'm trying to accomplish with this code is to output the array alphabet as a series of list items into an existing unordered list in the actual markup. I've got the array into list items, but I can't figure out how to tell it to append itself to an existing unordered list <ul id="itemList"></ul>.
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
document.write('<li>' + alphabet[indexNum++] + '</li>');
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
Don't use document.write to do it. You should act like this:
function write_letters(){
var letters = "";
for (var i = 0; i < alphabet.length; i++ ) {
//Also I don't understand the purpose of the indexNum variable.
//letters += "<li>" + alphabet[indexNum++] + "</li>";
letters += "<li>" + alphabet[i] + "</li>";
}
document.getElementById("itemList").innerHTML = letters;
}
More proper way is to use DOM (in case you want full control of what's coming on):
function write_letters(){
var items = document.getElementById("itemList");
for (var i = 0; i < alphabet.length; i++ ) {
var item = document.createElement("li");
item.innerHTML = alphabet[i];
items.appendChild(item);
}
}
You can use a combination of createElement() and appendChild() to add new HTML elements within another HTML element. The code below should work for you:
<html>
<head>
<title>Script Test</title>
</head>
<body>
<ul id="itemList"></ul>
</body>
<script>
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
var myElement;
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
// Create the <LI> element
myElement = document.createElement("LI");
// Add the letter between the <LI> tags
myElement.innerHTML = alphabet[indexNum++];
// Append the <LI> to the bottom of the <UL> element
unorderedList.appendChild(myElement);
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
</script>
</html>
Note how the script exists below the body tag. This is important if you want your script to work the way you wrote it. Otherwise document.getElementById('itemList') will not find the 'itemList' ID.
Try to reduce the actions on the DOM as much as possible. Every appendChild on unorderedList forces the browser to re-render the complete page. Use documentFragement for that sort of action.
var frag = document.createDocumentFragment();
for (var i = alphabet.length; i--; ) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(alphabet[indexNum++]));
frag.appendChild(li);
}
unorderedList.appendChild(frag);
So there will be only one DOM action which forces a complete redraw instead of alphabet.length redraws

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