PLEASE DO NOT MARK THIS AS DUPLICATE! THIS IS THE ONLY PURE JAVASCRIPT APPROACH WITH INDIVIDUAL ID'S
How do I split a large block of text into individual spans with id's that go like this:
<span class="word" id="word0">Breaking </span>
<span class="word" id="word1">News. </span>
<span class="word" id="word2">Spring </span>
<span class="word" id="word3">is </span>
<span class="word" id="word4">here </span>
<span class="word" id="word5">to </span>
<span class="word" id="word6">stay. </span>
If the input was "Breaking News. Spring is here to stay."
I want to get the input from a specific div and output it into the same div. Please do not use jquery for this.
EDIT: Thanks to Scott Marcus, he gave me this code:
/* hw3a.js */
// your solution here
var button = document.getElementById('divideTranscript');
button.onclick = spanify();
var s = document.getElementById('transcriptText').innerHTML;
function spanify() {
var arry = s.split(" ");
var arry = s.split(/\s+/); // This will split on any group of whitespaces
var output = "";
var len = arry.length;
for(var i = 0; i < len; ++i) {
output += "<span class='word' id='word" + i + "'>" + arry[i] + "</span>" ;
}
s.innerHTML = output;
}
But it does not work?
var s = "Breaking News. Spring is here to stay.";
var arry = s.split(" "); // This will split on all single whitespaces
var arry = s.split(/\s+/); // This will split on any group of whitespaces
var output = "";
var len = arry.length;
for(var i = 0; i < len; ++i){
output += "<span id='word" + i + "'>" + arry[i] + "</span>" ;
}
alert(output);
// Or, to be more core DOM compliant
var d = document.createElement("div");
for(var i = 0; i < len; ++i){
var sp = document.createElement("span");
sp.setAttribute("id", "word" + i);
sp.textContent = arry[i];
d.appendChild(sp);
}
alert(d.innerHTML);
Related
I have this for loop
<script>
...
for(i = 0;i < json.length;i++){
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
</script>
I want to print a paragraph with a href on each loop, so i did this:
</script>
<a id="pLink">
<p id="pText">
</p>
</a>
It works but the thing is this only prints the last loop.
So i tried this inside the script
document.write("<a href=\"" + json[i].html_url + "\">");
document.write("<p>" + json[i].name + "</p>");
document.write("</a>");
instead of this:
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
And it prints everything i want but it replaces the whole page.
How can i do this? Do i need to create an id for every loop? Like "pText1, pText2, etc.
Create a container element for that loop, and add the html as you had in mind
<div id="container"></div>
Then in javascript
var container = document.getElementById('container');
var my_html = '';
for(var i = 0;i < json.length;i++){
my_html += '<a href="' + json[i].html_url + '\">';
my_html += '<p>'+ json[i].name + '</p>'
my_html += '</a>'
}
container.innerHTML = my_html;
What we are doing here is adding the content to a string as many times as needed and then add it to the container so it already has all the loops
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
If you want to use your this code, you have to write "+=" instead of the "=".
var json = [
{"name":"Name 1", "html_url": "http://www.example.com"},
{"name":"Name 2", "html_url": "http://www.example.com"},
{"name":"Name 3", "html_url": "http://www.example.com"}
];
for(var i = 0; i < json.length; i++){
document.getElementById("pText").innerHTML += json[i].name + "<br>";
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
<a id="pLink">
<p id="pText">
</p>
</a>
I will do it in the following way:
let json = [{'name':'Google','html_url':'https://www.google.com/'}, {'name':'Facebook','html_url':'https://www.facebook.com/'}, {'name':'Twitter','html_url':'https://twitter.com/?lang=en'}];
let item = document.querySelector(".pLink")
for(let j = 1; j<json.length; j++){
let cln = item.cloneNode(true);
document.body.appendChild(cln);
}
let aTag = document.querySelectorAll('a.pLink');
aTag.forEach(function(item, i){
let a = item.setAttribute("href",json[i].html_url);
let p = item.querySelector('.pText');
p.innerHTML = json[i].name;
})
<a class="pLink">
<p class="pText">
</p>
</a>
I got an array from json and I need to put each item in a <li> on my html
something like this :
names : {john, paul, ringo,george}
into <li>john</li>..
my code:
<div id="demo"></div>
script:
function onLocationsReceived(data) {
console.log("recievd");
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
document.getElementById("demo").innerHTML = sensorNames;
console.log(sensorNames);
}
}
on the concole.log it prints just fine..
document.getElementById("demo").innerHTML = '<li>' + sensorNames '</li>
something like that???
Using something like below
function onLocationsReceived(data){
var html="";
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
html+="<li>"+sensorNames+"</li>";
console.log(sensorNames);
}
document.getElementById("demo").innerHTML=html;
}
You can use syntax below
document.getElementById('demo').innerHTML ='<li>' + sensorNames + '</li>'
You should cache the iterative sensorNames into a var with the li and then replace the innerHTML:
var content = "",
sensorNames;
for (var i = 0; i < data[0].Sensors.length; i++) {
sensorNames = data[0].Sensors[i].Name;
content += "<li>" + sensorNames + "</li>";
}
document.getElementById("demo").innerHTML = content;
I'm beginner in coding. I've tried to find similar problem on SO but with no proper result.
I'm writting a code where HTML form sends its value to an object's property, then I want to print it in document using innerHTML method. I save object in array so then I can manipulate them.
Some problems appears when I add one more dimension to my array (arr[i][j] in code below - 2nd dimension will be needed further) - then object's properties change to "undefined" when printed. What should I do to get access to object's properties in array's 2nd dimension (using JS only)? This is my JS code:
var pro = 0;
var ctg = 1;
var arr = new Array(ctg);
arr[0] = new Array(pro)
function AddProduct() {
var n = document.getElementById('name').value;
var p = document.getElementById('price').value;
pro++;
for (i = arr[0].length; i < pro; i++) {
arr[0].push([{
name: n,
price: p
}]);
}
var content = '';
for (i = 0; i < arr.length; i++) {
for (j in arr[i]) {
content += arr[i][j].name + ' price is ' + arr[i][j].price + '<br>';
}
}
document.getElementById('p').innerHTML = content;
};
and HTML in body:
<p id="p"></p>
<input type="text" id="name" placeholder="name">
<br>
<input type="text" id="price" placeholder="price">
<br>
<input type="button" value="OK" onclick=A ddProduct()>
Try substituting
onclick="AddProduct()"
for
onclick=A ddProduct()
at html; and add [0] at
content += arr[i][j][0].name + ' price is ' + arr[i][j][0].price + '<br>';
for
content += arr[i][j].name + ' price is ' + arr[i][j].price + '<br>';
as you pushed an array containing an object to arr at first for loop. To reference the index of the array, use bracket notation to retrieve object at index 0 of array in arr
var pro = 0;
var ctg = 1;
var arr = new Array(ctg);
arr[0] = new Array(pro)
function AddProduct() {
var n = document.getElementById('name').value;
var p = document.getElementById('price').value;
pro++;
for (i = arr[0].length; i < pro; i++) {
arr[0].push([{
name: n,
price: p
}]);
}
var content = '';
for (i = 0; i < arr.length; i++) {
for (j in arr[i]) {
content += arr[i][j][0].name + ' price is ' + arr[i][j][0].price + '<br>';
}
}
document.getElementById('p').innerHTML = content;
};
<p id="p"></p>
<input type="text" id="name" placeholder="name">
<br>
<input type="text" id="price" placeholder="price">
<br>
<input type="button" value="OK" onclick="AddProduct()">
I'm having a bit of a problem. I'm trying to create a unordered list from a javascript array, here is my code:
var names = [];
var nameList = "";
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
nameList += "<li>" + names + "</li>";
document.getElementById("name").innerHTML = nameList;
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="submit()">
<br>
<br>
<div id="name"></div>
For example, if I post 2 names, Name1 and Name2 my list looks like this:
•Name1
•Name1,Name2
I want it to look like this:
•Name1
•Name2
If you look at your code, you are only creating one li with all your names as the content. What you want to do is loop over your names and create a separate li for each, right?
Change:
nameList += "<li>" + names + "</li>";
to:
nameList = "";
for (var i = 0, name; name = names[i]; i++) {
nameList += "<li>" + name + "</li>";
}
If you are interested in some better practices, you can check out a rewrite of your logic here: http://jsfiddle.net/rgthree/ccyo77ep/
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
document.getElementById("name").innerHTML = "";
for (var I = 0; I < names.length; I++)
{
nameList = "<li>" + names[I] + "</li>";
document.getElementById("name").innerHTML += nameList;
}
}
You are using an array, when you print an array JavaScript will show all the entries of the array separated by commas. You need to iterate over the array to make it work. However you can optimize this:
var names = [];
function displayUserName()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="displayUserName()">
<br>
<br>
<div id="name"><ul></ul></div>
In this example the HTML is syntactically correct by using the UL (or unordered list) container to which the lis (list items) are added.
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
This line selects the div with the name: name and its first child (the ul). It then appends the LI to the list.
As #FelixKling said: avoid using reserved or ambiguous names.
<div>
<label for="new-product">Add Product</label><br /><br /><input id="new-product" type="text"><br /><br /><button>Add</button>
</div>
<div>
<ul id="products">
</ul>
<p id="count"></p>
</div>
var products = [];
var productInput = document.getElementById("new-product");
var addButton = document.getElementsByTagName("button")[0];
var productListHtml = "";
var abc = 0;
addButton.addEventListener("click", addProduct);
function addProduct() {
products.push(productInput.value);
productList();
}
function productList() {
productListHtml += "<li>" + products[abc] + "</li>";
document.getElementById("products").innerHTML = productListHtml;
abc++;
}
I'm creating some ul and span tags dynamically. Now, I'm trying to add content dynamically as well through a click function. The tags gets created inside a ul but the content doesn't get inserted. Here is the code for it:
<div class="main"></div>
<div class="content-list"><ul class="information"> </ul></div>
Here's the Javascript with the function and the listener:
var $contentHandler = $(".content-list");
var $mainHandler = $(".main");
var $infoHandler = $(".information");
var circleCounter = 1;
$mainHandler.click(function() {
var htmlString = "<li class='" + circleCounter + "'> <span class='circle-color'> var color = <div class='circle-color-input' contentEditable autocorrect='off'> type a color</div> ; </span> <br> <span class='circle-radius'> This is supposed to change </span> <br> <span class='circle'> This is supposed to change </span> </li>"
$infoHandler.append(htmlString);
updateList();
circleCounter++;
});
function updateList() {
var listItems = $('.information').find('li#' + circleCounter);
var len = circleCounter;
for (var i = 0; i < len; i++) {
//We create one reference. This makes looking for one element more effective. Unless we need to search for a particular element
var currentItem = circles[i];
var updateStringRadius = "var radius = " + circleCounter + ";";
var updateStringCircle = "circle (" + circleCounter + " ," + circleCounter + ", radius)";
//This is the div Item for the particular div of each element
var divItem = $(listItems[i]);
var radiusItem = divItem.find("span.circle-radius");
var circleItem = divItem.find("span.circle");
radiusItem.text(updateStringRadius);
circleItem.text(updateStringCircle);
// divItem.text(updateString);
var $circleRadiusHandler = $(".circle-radius");
}
}
Any suggestions in how to make it work. Here's a JSFiddle for that:
http://jsfiddle.net/mauricioSanchez/wL6Np/1/
Thank you kindly,
You just need to change:
var listItems = $('.information').find('li#' + circleCounter);//this searches by id
//To:
var listItems = $('.information').find('li.' + circleCounter);//this searches by class`
//And remove:
var currentItem = circles[i];
Why are you trying to edit your HTML after you've defined it? Why not use a template like this:
var listItemClass = 'someclass',
typeOfColor = 'somecolor',
radiusOne = 'someradius',
radiusTwo = 'anotherradius';
var listItem = "<li class='{0}'> \
<span class='circle-color'> var color = \
<div class='circle-color-input' contentEditable autocorrect='off'> {1}</div> ; \
</span> \
<br> \
<span class='circle-radius'>{2}</span> \
<br> \
<span class='circle'>{3}</span> \
</li>";
listItem.format(listItemClass, typeOfColor, radiusOne, radiusTwo);
With the following format definition:
String.prototype.format = String.prototype.f = function () {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
This way, you don't have to worry about finding certain elements within your predefined structure after the fact. You're just replacing certain parts with whatever you specify.