How to add spans to every word in paragraph of text? - javascript

How to append a span to every word in a particular document div ("text")? New to using nodes in js. Keep getting message,
"object has no method append child..."
What am I missing? This is my code:
var y;
var words;
function get() {
y = document.getElementById("text").firstChild.nodeValue;
words = y.split(" ");
for (var x = 0; x < 3; x++)
{
var newSpan = document.createElement('span');
words[x].appendChild(newSpan);
}
}

You need to first fetch the dom element you want to append the words to,
elem = documents.getElementById("#some_container");
Then append the words to it
words.forEach(function(w) {
var new_span = document.createElement('<span>');
new_span.innerHTML = w;
elem.appendChild(new_span);
});

Related

Inserting text after a certain image using javascript

In one function I have a loop that creates 10 images using the createElement();. In the other function I have another loop that contains info that I need to add text after each picture but my code adds it at the end of all 10 pictures I need them to be after every corresponding picture.
This is the function that displays the text:
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
display.appendChild(span1);
}
}
I cant individually set the id of each image because i created them in js. Thanks for the help in advance and no jquery please
for (var x = 0; x<json.length;x++){
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
display.appendChild(image);
var a = document.getElementById("artist");
var y = document.getElementById("year");
var artist = document.getElementById("artist").selectedIndex;//index of value of the switch statement
var year = document.getElementById("year").selectedIndex;//index of value of the switch statement
var realYear = y[year].text;//Value of the selected text
var realArtist = a[artist].text;//Value of the selected text
var display = document.getElementById("Results");
}
This is my second loop. I want displayalbum to appear after every picture. I cannot combine them because of other complications in the code
Try to do something like that: plunker
function displayAlbum(){
for (var x = 0; x < 10 ; x++){ // change to json.length
var span1 = document.createElement("span");
span1.innerText = 'json[x].album';
span1.id = 'span'+x;
var display = document.getElementById("results");
display.appendChild(span1);
}
}
The loop where you are creating images, give a unique id to image like image.id = "picture" + x;
Then change displayAlbum() function to use corresponding image to place the span tag.
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
var img = document.getElementById("picture" + x); // use unique id of img to access it
if(img.nextSibling) { // if img is not the last node in 'results'
display.insertBefore(span1, img.nextSibling);
} else { // if img is the last node in 'results'
display.appendChild(span1);
}
}
}
You can achieve your goal with single loop and using Figure and FigCaption element , specifically created for this kind of display image with its description
var json = [{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test1"},{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test2"}];
for (var x = 0; x<json.length;x++){
var fig = document.createElement("figure");
var figCap = document.createElement("figcaption");
figCap.innerText = json[x].album;
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
fig.appendChild(image);
fig.appendChild(figCap);
display.appendChild(fig);
}
<div id="results">
</div>

Looping through a set of <p>'s one at a time

I'm trying to figure out how to count the number of p's so every time the button is pressed, it outputs to 0 to 1 until the maximum number of p's is counted.
var big_number = 999999;
var i;
var a = document.getElementsByTagName("p");
function function0() {
for (i=0; i < big_number; i++) {
document.getElementsByTagName("p")[i].innerHTML="text";
}
}
I want it to write to another p every time the button is pressed.
document.getElementsByTagName("p").length // number of p elements on the page
Is that what you were asking?
Make a generic tag adder function then call it:
function addTags(tagName,start, max, container) {
var i = start;
for (i; i < max; i++) {
var newp = document.createElement(tagName);
newp.innerHTML = "paragraph" + i;
container.appendChild(newp);
}
}
var tag = 'p';
var big_number = 30;
var i;
var a = document.getElementsByTagName(tag );
// **THIS is your specific question answer**:
var pCount = a.length;
var parent = document.getElementById('mydiv');
addTags(tag,pCount , big_number, parent);
// add 10 more
a = document.getElementsByTagName(tag );
pCount = a.length;
big_number = big_number+10;
addTags(tag,pCount , big_number, parent);
EDIT:
NOTE: THIS might be better, only hitting the DOM once, up to you to determine need:
function addTagGroup(tagName, start, max, container) {
var tempContainer = document.createDocumentFragment();
var i = start;
for (i; i < max; i++) {
var el = document.createElement(tagName);
el.textContent = "Paragraph" + i;
tempContainer.appendChild(el);
}
container.appendChild(tempContainer);
}
To find out how many <p> elements there are in the document you should use DOM's length property as below :-
var numP = document.getElementsByTagName("P").length;
or
var div = document.getElementById("myDIV");
var numP = div.getElementsByTagName("P").length;
To get number of element inside a tag.

Get the source of images from table cell

I am trying to get to the img.src of these table cells, but am going wrong somewhere.
var cell = newTable.rows.cells;
var content = newTable.getElementsByTagName('img');
var nodeArray = [];
for(var i = 0; i < content.length; ++i)
{
nodeArray[i] = content[i];
}
var listThem = $(this).attr('src');
console.log(listThem);
Use this :
var content = newTable.getElementsByTagName('img');
for(var i = 0; i < content.length; i += 1) {
var source = content[i]['src'];
//do something
}
getElementsByTagName() returns an array of dom elements.
To access the "src" attribute of a dom element, you can do this : element.src or element['src'];
source will contain the image source.

How to add DOM Element in for loop

How can I create new Element each time when (i) will be incremented:
for(int i = 0; i < 10; i++)
{
Element child = doc.createElement("xxx");
root.setAttribute("x", i * "xx");
doc.appendChild(child);
}
Using pure js
var div = document.getElementById("main");
for (var i = 0; i < 10; i++) {
var span = document.createElement("span");
span.setAttribute("class", "new");
span.innerHTML = "span" + i;
div.appendChild(span);
}​
HTML
​<div id="main"></div>​​​​​​​
Working example.
Cheers!!
Using java
Element child = null;
for(int i = 0; i < 10; i++)
{
child = doc.createElement("xxx" + i);//you can write a method with int parameter to get element name from somewhere else
doc.appendChild(child);
}
I hope this is what you wanted, by the way for text nodes you should use doc.createTextNode("A")

Break javascript loop

I have following code to use google images search API:
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 1; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
The problem is, it gives me 3 image results. How to break a loop and show only the 1st one instead of 3 images?
if I change for (var i = 1; i < results.length; i++) to for (var i = 3; i < results.length; i++) it shows only one image, but image shown is the 3rd one and I need to show 1st one :)
Please advice
Don't use a for loop at all. Just replace all instances of i with 0.
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
var result = searcher.results[0];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
0 means the first item returned (almost all number sequences in programming start at 0!) so all other results will be ignored.
When you only want one element, you don't need a for loop. You can access the first element of an array with
result = results[0];
Arrays are zero-based. So when it contains three images, the images are named results[0], results[1] and results[2].
use break statement. It will terminate the loop once the image is found and hence you will have only the first one.
for (var i = 1; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
//Berore the end of the loop
if(i==1)
{
break;
}
}

Categories

Resources