I have a js file with the following array
var fruits = [ "Apples","Oranges","Pears","Grapes","Pineapples","Mangos" ];
In my HTML file I want to create a container and write an ordered list containing all the fruits in the array to the container I just created, however I'm having serious trouble and I can't find much online help. I'm a beginner, this is what I have
<div class = "container1">
</div>
<h3>Fruits</h3>
<html>
<head>
<script src="Web Programming/Assignments/Assignment #3/assignment3/list.js"></script>
</head>
<body>
<div container1= "fruits"></div>
</body>
You should give the element an id, your custom html attribute would work as a selector, but the typical way would be the id. Then you can simple create some elements in a loop, giving them the element's text content:
var fruits = [ "Apples","Oranges","Pears","Grapes","Pineapples","Mangos" ];
var el = document.getElementById('fruits');
var ol = document.createElement('ol');
el.appendChild(ol);
fruits.forEach(function (fruit) {
var f = document.createElement('li');
f.appendChild(document.createTextNode(fruit));
ol.appendChild(f);
});
<div id="fruits"></div>
Just in case you insist on the container1=... you can select that with
var el = document.querySelector('div[container1="fruits"]');
Firstly include your script in your html file. At the bottom of the body.
Give your container id of container or as you like.
And code will be something like this:
var arrayFruits = ["bananas", "apples", "etc"];
var container = document.getElementById("container");
for (var i = 0; i < arrayFruits.length; i++) {
var list = document.createElement("li");
list.innerHTML = arrayFruits[i];
container.appendChild(list);
}
Related
I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>
I have I array of images src ["http://src1", "http://src2", "http://src3"]. I want for get all images from that array and manipulate them, for example placing them into a div?
var imgSrc = ["http://src1,http://src2,http://src3"];
var string = imgSrc[0];
console.log(string);
var array = string.split(",");
console.log(array);
var inHTML = '';
console.log(array[0]);
$.each(array, function(key, value){
var html = '<img src="'+ value[key]+'" align="center">';
inHTML += html;
});
$('div#item').html(inHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item"></div>
You can append the dynamically created Images from the array to a perticular div. Hope this helps...
HTML
<html>
<head>
</head>
<body>
<h1>Images</h1>
<div id="content">
</div>
<script src="app.js"></script>
</body>
</html>
JS
var imageSources = ["http://src1,http://src2,http://src3"]
imageSources.forEach(element => {
var img = document.createElement("img");
img.width = '300';
img.height = '300';
img.src = element;
document.getElementById("content").appendChild(img)
};
I think your array is somewhat like:
["http://src1","http://src2","http://src3"]
If I am right then you can do something like:
var y = x.map((key,value)=>{return ('<div>'+key+'</div>')});
y will be an array with the div tags containing images.
Hope, I understood your problem.
I want for get all images from that array and manipulate them, for
example placing them into a div
You can dynamically generate img elements and add them to a div.
To iterate through the array you could use forEach, creating the img elements within the loop using createElement and appendChild to append the image to the div
See example below, which should get you started.
var images = ["https://placehold.it/50x50","https://placehold.it/25x25","https://placehold.it/75x75"];
var target = document.getElementById('target');
images.forEach(function(imgSrc){
var newImg = document.createElement("img");
newImg.src = imgSrc;
target.appendChild(newImg);
})
<div id="target"></div>
Creating an Array:
You must use the following syntax to to create a JavaScript Array:
var array_name = [ item1, item2, ... ];
Or Using the JavaScript Keyword new:
var array_name = new Array( item1, item2, ... );
So your array must be like this:
var image_source = [ 'http://src1', 'http://src2', 'http://src3' ];
Access the Elements of an Array:
You refer to an array element by referring to the index number. for example this statement accesses the value of the first element in cars:
var first_image = image_source[ 0 ];
Example:
var image_source = [ 'http://img1', 'http://img2', 'http://img3' ];
document.getElementById( 'demo' ).innerHTML = image_source[ 1 ];
<div id="demo"></div>
I'm using following code for translation elements with data-i18next attribute:
const elementsToTranslate = document.querySelectorAll('[data-i18next]');
for (let i = 0; i < elementsToTranslate.length; i++) {
elementsToTranslate[i].innerText = i18next.t(elementsToTranslate[i].getAttribute('data-i18next'));
}
But it replaces all child elements.
I have h1 element with span child:
<h1 data-i18next="header-title" class="header__title">
<span data-i18next="header__subtitle" class="header__subtitle"></span>
</h1>
After running translation function it becomes:
<h1 data-i18next="header-title" class="header__title">translated-text</h1>
But I need child items to stay. Without jquery.
Result I need:
<h1 data-i18next="header-title">translated-title
<span data-i18next="header__subtitle">translated-span</span>
</h1>
Create a textnode and prepend it in the element. This should end up in the result you seek according to your edit.
The function i18next.t() is not known, since you did not provide it. Thus I replace it with the attribute text for now.
<html>
<head>
<script>
//Scope for the little translator and the list of textnodes
;(function(ns){
'use strict';
var _List = []; //Stores the created textnodes
//Removes the textnodes from the List
function _removeNodes(){
if(_List && _List.length){
for(var i=_List.length-1; i>=0; i--){
_List[i].parentNode && _List[i].parentNode.removeChild(_List[i])
};
_List = []
}
};
ns.Translator = {
Translate: function(){
_removeNodes();
const elementsToTranslate = document.querySelectorAll('[data-i18next]');
for (let i = 0; i < elementsToTranslate.length; i++){
var tE = elementsToTranslate[i];
var tText = tE.getAttribute('data-i18next'); //i18next.t(tE.getAttribute('data-i18next'));
var tN = document.createTextNode(tText);
_List.push(tN); //The node gets stored, so it can be removed again later
tE.insertBefore(tN, tE.firstChild)
}
}
}
}(window._ = window._ || {}));
window.onload = function(){
_.Translator.Translate()
_.Translator.Translate()
_.Translator.Translate()
}
</script>
</head>
<body>
<h1 data-i18next="header-title" class="header__title">
<span data-i18next="header__subtitle" class="header__subtitle"></span>
</h1>
</body>
</html>
Result:
<h1 data-i18next="header-title" class="header__title">header-title
<span data-i18next="header__subtitle" class="header__subtitle">header__subtitle</span>
</h1>
updated. I want to translate both: title and span inside it.
#caesay subtitle is span and it's better to put it inside
I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo
I want to convert this code into an array.
<div id="Parent">
<div class="childOne" ><span id="1dfgdffsf">ChildOne </span></div>
<div class="childOne" ><span id = "2sdfsf">ChildTwo</span> </div>
<div class="childOne" ><span id="3sdfsf">ChildThree </span></div>
<div class="childOne" ><span id="4dssfsf">ChildFour </span></div>
</div>
span id is dynamic. therefore i can't use it.please tell me how to convert it into an array.
You will have to loop over each element and push it into an array
//declare an array
var my_array = new Array();
//get all instances of the SPAN tag and iterate through each one
$('div#parent div.childOne span').each(function(){
//build an associative array that assigns the span's id as the array id
//assign the inner value of the span to the array piece
//the single quotes and plus symbols are important in my_array[''++'']
my_array[''+$(this).attr('id')+''] = $(this).text();
//this code assigns the values to a non-associative array
//use either this code or the code above depending on your needs
my_array.push($(this).text());
});
If you do not use a library, the following should work fine:
var result = [], matches = document.querySelectorAll("#Parent span");
for (var i = 0, l = matches.length; i < l; i++)
result.push(matches[i].getAttribute("id"));
Else if the document.querySelectorAll function is not supported:
var result = [], parent = document.getElementByID("Parent");
for (var i = 0, l = parent.childNodes.length; i < l; i++)
result.push(parent.childNodes[i].childNodes[0].getAttribute("id"));
If you wanted to get key/value pairs instead you can do the following:
var result = [], matches = document.querySelectorAll("#Parent span");
for (var i = 0, l = matches.length; i < l; i++)
result[matches[i].getAttribute("id")] = matches[i].text;
With jQuery it is as simple as a single line of code:
var result = $("#Parent span").map(function() { return $(this).attr("id"); }).get();
First of all, try to avoid naming id's and classes from capital letters.
Then try this:
var arr = [];
$('#parent').children().each(function(){
arr.push($(this).find('span').text());
}
maybe this is the best way currently
const array = Array.from(document.querySelectorAll('.childOne'));
Below Code May be help you :
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>
<script>
var elems = document.getElementsByTagName("div"); // returns a nodeList
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);
</script>
</body>
</html>
This would be simple one, as :
jQuery(function($) {
var anArray = [];
$("#Parent").find("span").each(function(){
anArray.push($(this).html());
});
alert(anArray);
});