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

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
}

Related

In a loop, find a span that is at the top level or a child

Here's the fiddle
Within a looping function I will get html strings that have a span element either at the top level or also it could be as a child within a div. How can I find it in either case?
I know find only searches children. Not even sure how to find it when it is in the top level, as in data2 below? If I did, then I guess I'd do a find first, and if it's length was 0, then do the search for the span in the top level.
var data1 = "<div class='form-group'><span class='editableColumn'>NAT</span><input type='text' class='editableColumn form-control' style='display:none' name='Lot' value='NAT'></div>";
var data2 = "<span class='editableColumn'>Yes</span><input type='checkbox' name='IsBackorder' class='editableColumn editor-active' style='display:none' checked='checked' value='true'>";
var myStringArray = [data1, data2];
var arrayLength = myStringArray.length;
$(document).ready(function() {
for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i]);
//Do something
var span = $(data1).find("span.editableColumn").text();
$("#" + i).text(span);
}
})
You can use .addBack() to do it in one line if you prefer that.
$(document).ready(function() {
for (var i = 0; i < arrayLength; i++) {
var span = $(myStringArray[i]).find("span.editableColumn").addBack("span.editableColumn").text();
$("#" + i).text(span);
}
})
http://jsfiddle.net/a21sk6dx/
If your HTML had parents, you could do: $(myStringArray[i]).parent().closest("span.editableColumn").text();
Since you don't, you either need to wrap your data2 in a , or try find then closest:
$(document).ready(function() {
for (var i = 0; i < arrayLength; i++) {
console.log();
//Do something
var span = $(myStringArray[i]).find("span.editableColumn").text();
if (!span) span = $(myStringArray[i]).closest("span.editableColumn").text();
$("#" + (i + 1)).text(span);
}
})
Also, watch out: You've got i=0, < arrayLength, so it would only run through 0 and 1, and you have your ID's as 1 & 2, hence the $("#" + (i + 1))

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

Instantiate new element class using javascript

How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.
You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.
var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.
With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}
Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}

Javascript: Strip tags with desired class

I use this function to stip tags in javascript
noTags = result.strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
but how can i only remove tags if the hay a desired class??
for example, from
Remove only tags with classes: 'tooltip_left', 'tooltip_right', 'tooltip_bottom' and keep ...
What about this: (js fiddle demo)
var StripTags = function (desiredClass)
{
var nodes = document.querySelectorAll('.' + desiredClass);
for (var i = 0; i < nodes.length; i++)
nodes[i].parentNode.removeChild(nodes[i]);
}
StripTags("tooltip_left");
StripTags("tooltip_right");
StripTags("tooltip_bottom");

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