Adding letters from a string array into each dynamic div - javascript

I am trying to add each letter of a word to dynamically generated divs .box and .boxIn but the code is just adding the last word to each box! How can I fix this, and why is his happening? And is there any way to merge two loops into one loop?
Here is the demo
And this is the code which I have:
var letters = [];
var str = "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 letters = str.split(",");
var word = "Test App";
for (var i = 0; i < word.length; i++) {
$('<div class="box"><div class="boxIn"></div></div>').appendTo(".wrapper");
}
for (var j = 0; j < word.length; j++) {
$('.boxIn').html(word.charAt(j)).addClass('animated fadeInDown');
}

That's because you are overriding html content of all the .boxIn elements, you should use the current iterator's index for selecting the target element:
$('.boxIn').eq(j).html(word.charAt(j)).addClass('animated fadeInDown');
http://jsfiddle.net/k4spypqj/
That being said there is no need to use 2 loops. You can set the generated element's content in the first loop using either text or html method.

Fairly simple to combine these which will make it more efficieent and get rid of the html over ride bug you have
var letters = [];
var str = "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 letters = str.split(",");
var word = "Test App";
for (var i = 0; i < word.length; i++) {
$('<div class="box"><div class="boxIn animated fadeInDown">'+
word.charAt(i)+'</div></div>').appendTo(".wrapper");
}
DEMO

The problem is the way you set the html. You select all elements with the class boxIn and set the char at position j to the html (of all elements).
To only set the char to to a single element you can limit the selection by using the .eq() function.
In your case that would be:
for (var j = 0; j < word.length; j++) {
$('.boxIn').eq(j).html(word.charAt(j)).addClass('animated fadeInDown');
}
If you want to merge your two loops, you can set the value directly in your html string:
for (var i = 0; i < word.length; i++) {
$('' + word.charAt(i) + '').appendTo(".wrapper").children('.boxIn').addClass('animated fadeInDown');
}
or if you would add it separatly:
for (var i = 0; i < word.length; i++) {
$('<div class="box"><div class="boxIn"></div></div>').appendTo(".wrapper").children('.boxIn').addClass('animated fadeInDown').html(word.charAt(i));
}
jsfiddle

Related

How can i set the attribute of an element in MVC

my view:
<........id="S" labelPos="1" labelText=""/>
I want to set the value for labelText dynalically from the controller. i have tried the following but it did not work:
for (var i = 0; i < keys.length; i++) {
var c = labelText[keys[i]].StreetName;
var d = document.getElementsByTagName("S");
d.setAttribute("labelText", c);
}
Please change your document.getElementsByTagName("S");to document.getElementById("S") see if it works.
for (var i = 0; i < keys.length; i++) {
var c = labelText[keys[i]].StreetName;
var d = document.getElementById("S");
d.setAttribute("labelText", c);
}
First query your elements in DOM, querying in loop is not good practice, so:
var elements = document.getElementsByTagName("span");//span is example element
Or:
var elements = document.quertSelectorAll("selector");//your elements by selector
Use it in loop
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute("labelText", labelText[elements[i].getAttribute("labelPos")].StreetName);
}
I came to the conclusion that Your labelPos attribute is index of labelText array, this would be logical. So in above code I set attrbute from labelText array by labelPos value as key.
Second possibility if DOM elements are in the same order as labelText array:
for (var i = 0; i < elements.length; i++) {
//we take i element in DOM and set it StreetName from i element in labelText array
elements[i].setAttribute("labelText", labelText[i].StreetName);
}

Replacing <h2> tags with <p> tags, every other <h2> is skipped

I am working on an assignment and I have ran into some issues. We have to essentially convert an <h2> tag using javascript into a <p> tag while making sure it maintains all of its attributes.
I have come up with the following
var numElements = document.getElementsByTagName("h2").length;
for (i=0; i<numElements; i++){
var curr = document.getElementsByTagName("h2")[i];
var updated = document.createElement("p");
for (j = 0; j < document.getElementsByTagName("h2")[i].attributes.length; j++){
updated.setAttribute(curr.attributes.item(j).name, curr.attributes.item(j).value);
}
updated.innerHTML = curr.innerHTML;
curr.parentNode.replaceChild(updated, curr);
}
Now this somewhat works, but I am not sure why I am getting issues with it. The bug that happens is that this only works on every other <h2> tag. So if I have 3 tags within a body, it will only perform this function on first and third tags.
I am not looking for a jQuery answer.
On your second trip through the loop, i == 1, so you'll grab the second element from the list.
But it's a new list, that no longer includes the element you've already replaced. The old second element is now at i == 0, never to be touched.
The easiest way to avoid this? Work the list backwards:
var elements = document.getElementsByTagName("h2");
var numElements = elements.length;
for (i = numElements - 1; i >= 0; i--) {
var curr = elements[i];
var updated = document.createElement("p");
for (j = 0; j < curr.attributes.length; j++){
updated.setAttribute(curr.attributes.item(j).name, curr.attributes.item(j).value);
}
updated.innerHTML = curr.innerHTML;
curr.parentNode.replaceChild(updated, curr);
}
var elements = document.getElementsByTagName("h2");
var numElements = elements.length;
for (i = numElements - 1; i >= 0; i--) {
var curr = elements[i];
var updated = document.createElement("p");
for (j = 0; j < curr.attributes.length; j++) {
updated.setAttribute(curr.attributes.item(j).name, curr.attributes.item(j).value);
}
updated.innerHTML = curr.innerHTML;
curr.parentNode.replaceChild(updated, curr);
}
.something {
background-color: yellow;
}
<h2>The first h2</h2>
<h2 style="text-decoration: underline">And the second</h2>
<h3 class="something">And the third</h3>

Loop through array and apply text to n:th element

I got an array like so: ["abc", "cde", "efg"].
I want to loop through a set of elements and apply the strings from this array to each n:th (the length of the array) element.
<p>abc</p>
<p>cde</p>
<p>efg</p>
All I've managed is how to loop and apply the same string (the last one) to each element like:
<p>efg</p>
<p>efg</p>
<p>efg</p>
EDIT:
Currently I'm working with something like this:
for (var j = 0; j < noOfTableCells.length; j++) {
var heading = "";
for (var k = 0; k < myArray.length; k++) {
heading = headingArray[k];
}
}
But I can't figure out how to get it to every n:th (3rd in this case) element.
See the jsfiddle:
var elements = ["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
});
elements.forEach(function(element) {
$('body').append(element);
});
Or you could shorten it:
["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
}).forEach(function(element) {
$('body').append(element);
});
This uses jQuery. If you want to be a super random badass, you can do this (jsfiddle):
var elements = ["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
}),
parser = new DOMParser();
elements.forEach(function(element) {
document.body.appendChild(parser.parseFromString(element, "text/xml").firstChild);
});
There are a 1000 other random, or 1000 other more efficient, solutions to this. Pick your poison.
When looping through the other elements, if there is a numbering system associated with that, you can use the numbering system. Otherwise, you can loop through those elements with a C-style for loop, as follows:
var myArray = ["abc", "cde", "efg"];
var i;
for (i = 0; i < myArray.length; i++) {
var j = i % 3;
j = (i - j) + 2;
//do something with the element that you wanted
//do something with myArray[j];
}
Eventually solved it with the following:
var laps = totalItems / myArray.length;
for (var row = 0; row < laps; row++) {
for (var cell = 0; cell < myArray.length; cell++) {
//Do the stuff
}
}

Populating a select element with comma-separated values using for loop

I have a bunch of comma-separated values stored as strings in a JSON file. My aim is to split these values to populate a select element which is based on Selectize.js. Code (excerpt) looks as follows:
var options = {};
var attr_split = data.attributes['Attribute1'].split(",");
var options_key;
for (var i = 0; i < attr_split.length; i++) {
options_key = attr_split[i]
}
var options_values = {
value: options_key,
text: options_key,
}
if (options_key in options)
options_values = options[options_key];
options[options_key] = options_values;
$('#input').selectize({
options: options,
});
Although this seems to work, the output in the select element only shows the last iterations done by the for loop. As per here
and here, I've tried
for (var i = 0; i < attr_split.length; i++) {
var options_key += attr_split[i]
}
but this throws me undefined plus all concatenated strings without the separator as per the following example:
undefinedAttr1Attr2Attr3
When I simply test the loop using manual input of the array elements everything appears fine:
for (var i = 0; i < attr_split.length; i++) {
var options_key = attr_split[0] || attr_split[1] || attr_split[2]
}
But this is not the way to go, since the number of elements differs per string.
Any idea on what I'm doing wrong here? I have the feeling it's something quite straightforward :)
when you declare 'options_key' ,you are not initializing it.so its value is undefined .when you concatenate options_key += attr_split[i] .in first iteration options_key holds undefined.so only you are getting undefinedAttr1Attr2Attr3.
so declare and initialize options_key like.
var options_key="";
and in your loop
for (var i = 0; i < attr_split.length; i++)
{
options_key = attr_split[i]
}
Everytime you replace options_key with value of attr_split[i].so after the loop it will contain last element value.corrected code is
for (var i = 0; i < attr_split.length; i++)
{
options_key += attr_split[i]
}
Just change var options_key; to var options_key="";
The reason you are getting undefined is because you have not defined the variable properly.
Here is a working example
var attr_split = "1,2,3,4".split(",");
var options_key="";
for (var i = 0; i < attr_split.length; i++) {
options_key += attr_split[i]
}
alert(options_key);
var options_values = {
value: options_key,
text: options_key
}
alert(options_values);

javascript trying to remove all things with certain tags

I'm trying to use javascript to remove everyhting with button or input tags from a page... So far my code removes some of them and I dont know why. It only removes one checkbox out of many, and 2 buttons (there are 3 buttons)
var buttons = document.getElementsByTagName("button");
for (var j = 0; j < buttons.length ; j++)
{
buttons[j].parentNode.removeChild(buttons[j]);
}
var checkboxes = document.getElementsByTagName("input");
for (var j = 0; j < buttons.length ; j++)
{
checkboxes[j].parentNode.removeChild(checkboxes[j]);
}
var checkboxes = document.getElementsByTagName("input");
for (var j = 0; j < buttons.length ; j++) // You use the wrong variable here
{
checkboxes[j].parentNode.removeChild(checkboxes[j]);
}
Should be;
for (var j = 0; j < checkboxes.length ; j++)
Regarding to the undeleted button, maybe it's because it's an input type="button" and not a <button>?
Note that document.getElementsByTagName("input"); will get and delete later all the inputs, not just the checkboxes!
May I suggest you using a javascript library like jQuery? you could have done this will one line of code with no problems:
$('input[type="button"], input[type="checkbox"], button').remove();
document.getElementsByTagName returns a live NodeList. That means, when you remove the first element, a) the length decreases and b) the (first) item of the list is shifted.
There are two possibilities to work around that:
always remove the last element. The NodeList is in document order, so that will work:
for (var i=buttons.length-1; i>=0; i--) // var i=buttons.length; while(i--)
buttons[i].parentNode.removeChild(buttons[i]);
always remove the first element, and don't run an index until the length:
while (buttons.length) // > 0
buttons[0].parentNode.removeChild(buttons[0]);
It also would work with jQuery and co, because they copy the NodeList items in a static array. You can do that yourself as well:
var staticButtons = Array.prototype.slice.call(buttons);
for (var i=0; i<staticButtons.length; i++)
staticButtons[i].parentNode.removeChild(staticButtons[i]);
or you use a document selection method that returns a static NodeList right away, like querySelector:
var staticList = document.querySelectorAll("button, input");

Categories