List all items from a for loop with javascript - javascript

I'm looking for a way to list each firstname from the below loop. Currently it loops through each firstname stoping at the last which is Jack and only displaying that. I want it to display all of them like: John, Jane, Joe
var person = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}];
for (var i = 0; i < person.length; i++) {
document.getElementById("demo").innerHTML = person[i].firstName;
}
Can anyone advise on how I would do this?

The problem is that your are overwriting the innerHTML value, instead that you need to append your values to innerHTML property using '+':
var person = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}];
var demo = document.getElementById("demo");
for (var i = 0, len = person.length; i < len; i++) {
demo.innerHTML += person[i].firstName + ' ';
}
Check out this codepen. I have add some modifications to make the code more performant.

Please take a look at this code:
var person = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}],
html = "";
for (var i = 0; i < person.length; i++) {
html += person[i].firstName;
}
document.getElementById("demo").innerHTML = html;
You are overwriting each time with the innerHTML because you are not using '+='. I like to create a string beforehand and set it to nothing. Then you can add everything to that and only need to call innerHTML once.
Hope this helps!

here's another way to do it using a more functional style
"use strict";
var people = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}];
var node = document.getElementById('demo');
node.innerHTML = people.map(function(person){
return person.firstName;
}).join(', ');
#demo {
padding: 1em;
background-color: #def;
border: 1px solid gray
}
<div id="demo"></div>

Related

How to change innerHTML of each item in a list of webelements with nested classes

I am trying to make a javascript webextension that adds a couple numbers eg. "123" to the end of the inner text of a hyperlink text to each product on a shopping website, http://www.tomleemusic.ca
for example, if i go to this link, http://tomleemusic.ca/catalogsearch/result/?cat=0&q=piano
I want to add some numbers to the end of each product's name.
name of product and its nested hyperlink
so far, I have attempted the following code but it does not produce any results. Thanks for helping :)
var products= document.querySelector(".category-products, .products-
grid category-products-grid itemgrid itemgrid-adaptive itemgrid-3col
centered hover-effect equal-height");
var productslist = products.getElementsByClassName("item");
for (var i = 0; i < productslist.length; i++) {
productslist[i].getElementsByClassName("product-name").innerHTML =
productslist[i].getElementsByClassName("product-name").innerHTML +
"1234";
}
Your query is wrong and you should use querySelectorAll instead of querySelector for fetching all elements matching the query.
Below is the code required as per given site:
var productsListLink = document.querySelectorAll(".products-grid .item .product-name a:not(.product-image)");
for (var i = 0; i < productsListLink.length; i++) {
var a = productsListLink[i];
var name = a.innerHTML || "";
name += "1234";
a.innerHTML = name;
a.setAttribute('title', name);
}
I guess I found what you needed.
var products = document.querySelector(".category-products .products-grid.category-products-grid.itemgrid.itemgrid-adaptive.itemgrid-3col.centered.hover-effect.equal-height");
var productslist = products.getElementsByClassName("item");
for (var i = 0; i < productslist.length; i++) {
var productName = productslist[i].getElementsByClassName("product-name")[0].firstChild;
productName.innerHTML = productName.innerHTML + "1234";
}

Creating Grid on the fly with jquery

I'm new to frontend and I'm trying to practice doing this simple task: I have to create a grid on the fly that is n * n (n being inputed by the user).
I succesfully created a fix sized grid, but my problem is when trying to do this dynamically.
This is the code I wrote for a 3*3 grid: http://jsfiddle.net/y7c2h8yk/
For trying to create it dynamically I wrote the following function:
var setGridDimensions = function(n) {
// emptying current grid
$(".row").empty();
var $grid = $("#grid");
for (var i = 0; i < n; i++) {
// adding row
$grid.append('<div class="row">');
// adding each to element to row
**var $row = $(".row")[i];**
for (var j = 0; j < n; j++) {
$row.append('<div class="col"></div>');
}
}
};
Now, I understand there is a problem with line var $row = $(".row")[i]. What I need is inside the loop first create the row, then select the row created and then loop again and create each column. How can i do that ?
Any help would be really appreciated. Thanks.
You don't have to force jQuery to search for the .row element in the DOM tree n times. You have easy way to cache the element by setting it as variable.
Another thing, is that you should empty() the whole #grid element instead of .row. empty() method remove contents of the element, but not the element itself.
Alternatively, you could remove rows using $(".row").remove();
.empty() reference
.remove() reference
Code (I would however use the next one)
var setGridDimensions = function(n) {
var $grid = $("#grid").empty();
for (var i = 0; i < n; i++) {
// create .row and cache it setting as '$row' variable:
var $row = $('<div class="row"/>').appendTo($grid);
for (var j = 0; j < n; j++) {
$row.append('<div class="col"></div>');
}
}
};
DEMO
This would be faster than the one above, as it's single DOM modification:
var setGridDimensions = function(n) {
var html ='';
for (var i = 0; i < n; i++) {
html += '<div class="row">';
for (var j = 0; j < n; j++) {
html += '<div class="col"></div>';
}
html += '</div>';
}
// modify the DOM only once:
$("#grid").html(html);
};
DEMO
$(".row")[i] get the HTML element. So late, the $row.append('<div class="col"></div>'); will not work since .append() is a jQuery method.
If you want to select a specific index and keep it as a jQuery object, use .eq() :
var $row = $(".row").eq(i);
for (var j = 0; j < n; j++) {
$row.append('<div class="col"></div>');
}
Here's a way to do it without jQuery.
https://jsfiddle.net/lemoncurry/evxqybaL/1/
<div id="grid-holder"></div>
-
#grid-holder {
width: 100%;
}
.row {
clear: left;
background-color: red;
}
.cell {
width: 50px;
height: 50px;
border: 1px dashed blue;
float: left;
}
-
var gridly = function (n) {
var grid = document.getElementById("grid-holder");
for (var i = 0; i < n; i++) {
var row = document.createElement('div');
row.classList.add("row");
grid.appendChild(row);
for (var j = 0; j < n; j++) {
var cell = document.createElement('div');
cell.classList.add("cell");
row.appendChild(cell);
}
}
}
gridly(5);
use isotope http://isotope.metafizzy.co/ it uses the help of Javascript but it is very popular, so you will find plenty of docs
if you find it very complicated then there are many premium plugins that based their development on isotope already, for example the Media Boxes http://codecanyon.net/item/media-boxes-responsive-jquery-grid/5683020

Replace a space within a SPAN tag with a BR tag

I need to replace the space between the 2 words with a BR tag. I've tried quite a few things, this one I thought would work, but the original script only does it to the first item. :( I need it to replace it on all the menu items.
It's for menu text on a CMS, so I won't know what the text is going to be. All I know is that it will always be no more than 2 words.
I can use either JS or jQuery.
Demo here: JS Bin Link
HTML:
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
JavaScript:
// Doesnt work
// var span = document.getElementsByTagName(".navtext");
// Only works for the first one
var span = document.querySelector(".navtext");
// Doesnt work
// var span = document.querySelectorAll("navtext");
function space() {
var elem = document.createElement("br");
// elem.className = "space";
// elem.textContent = " ";
return elem;
}
function replace(elem) {
for(var i = 0; i < elem.childNodes.length; i++) {
var node = elem.childNodes[i];
if(node.nodeType === 1) {
replace(node);
} else {
var current = node;
var pos;
while(~(pos = current.nodeValue.indexOf(" "))) {
var next = current.splitText(pos + 1);
current.nodeValue = current.nodeValue.slice(0, -1);
current.parentNode.insertBefore(space(), next);
current = next;
i += 2;
}
}
}
}
replace(span);
I think, you dont want to use jQuery. Well, Here is quick solution:
var elms = document.querySelectorAll(".navtext");
for(var i=0; i<elms.length; i++){
elms[i].innerHTML = elms[i].innerHTML.replace(/\s/gi, "<br />");
}
Here is the jsfiddle: http://jsfiddle.net/ashishanexpert/NrTtg/
using jQuery you can do this:
$("span.navtext").each(function(){
$(this).html($(this).text().replace(/ /g,"<br />"));
})
If you install jQuery you can make it all more simple. Follow the installation instructions and then the code you'll need is something like:
jQuery(function($) {
// for each navtext run the described function
$(".navtext").each(function() {
// "this" represents the navtext
// replace all " " with "<br/>" from this's html
var code = $(this).text();
code = code.replace(" ", "<br/>");
// update this's html with the replacement
$(this).html(code);
});
});
Someone on twitter provided me with a fix, which was exactly like what Ashish answered.
var spans = document.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}
But that would quite work for me, but it did give me my answer! So thanks to Pete Williams
This is the code I went with:
var spans = document.querySelectorAll('.navtext');
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}

Javascript. It is possible to add id on splitted word?? using word.split("")

var wtc = document.getElementById("sw").value;
var cw = wtc.split("").join(' ');
cw.toString();
var x=document.getElementById("demo");
x.innerHTML=cw;
I have this code. how can i add id to the splitted(am i right on my term??) word.. it is possible?
I want is to add id on each letter that is splited. I dont know the exact number of letter because it's depend on the user's inputted word.
for example. i have this word from split.
[W][O][R][M]
i want it to be something it this. or anything that have an id :)
<div id="DIVtext1">W</div>
<div id="DIVtext2">O</div>
<div id="DIVtext3">R</div>
<div id="DIVtext4">M</div>
Thanks!
do you mean something like:
var word = "WORM".split("");
var demoEle = document.getElementById("demo");
for(var w = 0, len = word.length; w < len; w++) {
var divEle = document.createElement("div");
divEle.id = "DIVtext"+(w+1);
divEle.onclick = (function(v) {
return function() { copyDiv( "DIVtext" + (v+1) ) };
})(w);
divEle.innerHTML = word[w];
demoEle.appendChild( divEle );
}
Demo: jsFiddle
Updated Demo:: jsFiddle Updated
You could use a loop (for(i=0;i<splittedArray;i++)) and jQuery to add div tags to the dom with the innerHtml being the word.
Basically, once you have it in your array you can put it wherever you want. I find that jQuery makes it easy; however, you could also do it through jscript alone.
This can be achieved pretty easily using jQuery.
var letters = $('#sw').val().split('');
$.each(letters, function(i, letter) {
$('<div />', {
id: 'DIVtext'+ i,
text: letter
}).appendTo('#demo');
});
JSFiddle
If jQuery isn't an option, here's what you can do with vanilla JS.
var letters = document.getElementById('sw').value.split(''),
demo = document.getElementById('demo');
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('div');
letter.innerHTML = letters[i];
letter.id = 'DIVtext'+ i;
demo.appendChild(letter);
}
JSFiddle

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

Categories

Resources