Using DOM to append newlines in a paragraph - javascript

This may be a more basic question as I am learning/practicing using the DOM. But I have the following:
var demo_div = document.createElement("div")
demo_div.classList.add("demo")
var p_div = document.createElement("p")
var br = document.createElement("br")
for(let i = 0; i < 100; i++){
if (i % 5 == 0){
var text = document.createTextNode("meow")
}
else{
var text = document.createTextNode("woof")
}
p_div.appendChild(text)
p_div.appendChild(br)
}
demo_div.appendChild(p_div)
document.body.appendChild(demo_div)
I'm trying to create a div with the class = "demo" and then append a child node which is a paragraph to it. The paragraph will have 100 lines but every 5th line will have a different value.
That part wasn't hard at all the part I'm confused about is when I append the break to the paragraph, after each line is appended, the break doesn't actually work. Instead the break shows up at the end of the loop (As seen in the inspector). Any insight would be appreciated. Thanks.

You need to create a unique <br> element for each line break that you
want applied. Currently you're reusing the same <br> element which causes that same element to shift from it's last position to the next point in the text that you place it (via appendChild()).
Consider adding var br = document.createElement("br") inside your loop construct as shown:
var demo_div = document.createElement("div")
demo_div.classList.add("demo")
var p_div = document.createElement("p")
for(let i = 0; i < 100; i++){
if (i % 5 == 0){
var text = document.createTextNode("meow")
}
else{
var text = document.createTextNode("woof")
}
// Create a new br element for each loop iteration, and append it
// to your div like so:
var br = document.createElement("br")
p_div.appendChild(text)
p_div.appendChild(br)
}
demo_div.appendChild(p_div)
document.body.appendChild(demo_div)

You're only every creating one br - see how its creation is outside of the loop, rather than inside of the loop. When you call appendChild with an element that already exists in the DOM, the element is removed from its previous location and appended to the new parent.
Create the <br> inside the loop instead, just like you're doing with text:
var demo_div = document.createElement("div")
demo_div.classList.add("demo")
var p_div = document.createElement("p")
for(let i = 0; i < 100; i++){
var br = document.createElement("br")
if (i % 5 == 0){
var text = document.createTextNode("meow")
}
else{
var text = document.createTextNode("woof")
}
p_div.appendChild(text)
p_div.appendChild(br)
}
demo_div.appendChild(p_div)
document.body.appendChild(demo_div)

Related

Insert HTML element based on length of other element in for Loop

So I want to insert a span element x times based on the length of another html element as with a for loop. I am getting the correct amount returned but I get undefined in the html. I know I am doing something wrong in the loop, but can't see where? I have looped over arrays and returned the value before via a for loop, but inserting an element based on the count loop I have not. So I should be inserting the <span class="pagination-bullet"></span> say 4 times based on count. In html i get <<s<sp<spa So definitely something is not right.
var counterElem = document.querySelectorAll('.slider-carousel-slide');
var count = counterElem.length;
var paginationCount = count;
var parentElem = document.querySelector('#main-carousel-pagination');
var paginationElement = document.createElement('SPAN');
paginationElement.innerHTML = '<span class="pagination-bullet"></span>';
var insert = '';
for (i = 0; i < count; i++ ) {
insert += `<span class="swiper-pagination-bullet">`[i];
parentElem.append(insert);
}
So what I would expect is if count = 4, then the html would be:
<span class="pagination-bullet"></span>
<span class="pagination-bullet"></span>
<span class="pagination-bullet"></span>
<span class="pagination-bullet"></span>
When you are doing xxxxx[0] you are saying give me the first index of the string. Hence why you are seeing that weird output.
Assuming you want the number, you would use ${} in your string template literal.
insert += `<span class="swiper-pagination-bullet">${i}</span>`;
without the number
insert += `<span class="swiper-pagination-bullet"></span>`;
Can also build the string without the loop.
var insert = Array(count).fill('<span class="swiper-pagination-bullet"></span>').join();
parentElem.innerHTML = insert;
Example:
var counterElem = document.querySelectorAll('.slider-carousel-slide');
var count = counterElem.length;
var paginationCount = count;
var parentElem = document.querySelector('#main-carousel-pagination');
var paginationElement = document.createElement('SPAN');
paginationElement.innerHTML = '<span class="pagination-bullet"></span>';
var insert = "";
for (i = 0; i < count; i++ ) {
insert += "<span class=\"swiper-pagination-bullet\">" + [i] + "</span>";
}
parentElem.append(insert);

How can I make a different innerText for every DIV created in JavaScript?

I have one small problem in JS. I need to create around seven DIVs with a for function, but each div's content (here is innerText) must be different. Is there any way to do it with a function, without modifying each and every div by hand? If I put it inside the for function, the innerText will be the same.
Below is my code:
for (let i = 0; i < 7; i++) {
const innerDiv = document.createElement("div");
innerDiv.id = "innerDivID";
innerDiv.classList.add("innerDivClass");
innerDiv.innerText = 1;
outsideCaroussel.appendChild(innerDiv);
}
Note: outsideCaroussel is another div inside the Wrapper.
At least you should put i to the div as a text:
for (let i = 0; i < 7; i++) {
const innerDiv = document.createElement("div");
innerDiv.id = "innerDivID";
innerDiv.classList.add("innerDivClass");
innerDiv.innerText = i;
outsideCaroussel.appendChild(innerDiv);
}

Adding style tags around specific characters only

I am trying to add inline styling to only numbers in paragraph elements. For example:
<p>This paragraph has the numbers 1 and 2 in it.</p>
So in this instance, I would want to put <span class="style">1</span>and <span class="style">2</span>. Around the two numbers in that paragraph.
I am trying to write a javascript to accomplish this so I don't have to go back into the document I'm working on and manually add the styling tags around each number, as the document is very long.
So far this is what I wrote, but I'm having difficulty figuring out what to do for the next step on how to incorporate the edits back into the paragraph HTML.
let regEx=/[0-9]/g;
let list = [];
let paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
let html = paragraphs[i].innerHTML;
list.push(html);
}
// all paragraphs into one string.
let joined = list.join(' ');
// all the numbers in the paragraphs stored in array
let numbers = joined.match(regEx);
// define array for styling edits
let edits = [];
// adding the styling tags to each num
numbers.forEach(function(num){
edits.push('<span class="style">' + num + '</span>');
// outputs ["<span class='style'>3</span>", "<span class='style'>7</span>", "<span class='style'>4</span>", "<span class='style'>5</span>"]
});
// need to insert edits into paragraph html
If anyone can offer any suggestions on how I might be able to accomplish this that would be great, I am still relatively new to working with JS.
const paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
const regEx=/([0-9])/g;
const newHtml = paragraphs[i].innerHTML.replace(regEx, '<span class="style">$1</span>');
paragraphs[i].innerHTML = newHtml;
}
I updated your regex to put the number in a group, then in the string replace you can reference that group, since there is only one it will be $1. As you can see in the replace we are wrapping that with the appropriate span and then plugging it right back into the innerHTML.
I did notice that your regex is only capturing single digit numbers, if you wanted to capture multi-digit numbers, you could update your reg ex like this: /([0-9]+)/g.
I created a simple jsfiddle to show you how it works: https://jsfiddle.net/andyorahoske/dd6k6ekp/35/
I broke out the most fundamental part of this into a reusable function that you may find helpful in other contexts.
/**
* Wraps numbers in a string with any provided wrapper.
* #param {String} str A string containing numbers to be wrapped.
* #param {String} wrapper A string with placeholder %s to define the wrapper. Example - <pre>%s</pre>
* #return {String} The original string with numbers wrapped using the wrapper param.
*/
function wrapNumbers(str, wrapper) {
var numbersInStr = str.match(/\d+/g) || [];
var chunks = [];
var segmentStart = 0;
for(var i = 0; i < numbersInStr.length; i += 1) {
var number = numbersInStr[i];
var indexOfNumber = str.indexOf(number);
var fWrapper = wrapper.replace('%s', number);
chunks.push(str.slice(segmentStart, indexOfNumber));
chunks.push(fWrapper);
segmentStart = indexOfNumber + number.length;
}
if(segmentStart < str.length) {
chunks.push(str.slice(segmentStart, str.length));
}
return chunks.join('');
}
To use this in your use case it might look like the following:
var paragraphs = document.getElementsByTagName("p");
var wrapper = '<span class="style">%s</span>';
for(var i = 0; i < paragraphs.length; i += 1) {
var paragraph = paragraphs[i];
paragraph.innerHTML = wrapNumbers(paragraph.innerHTML, wrapper);
}
Codepen: https://codepen.io/bryceewatson/pen/vRqeVy?editors=1111
Here's a new code https://jsfiddle.net/fazanaka/au4jufrr/1/
var element = document.getElementById('text'),
text = element.innerText,
wordsArray = text.split(' '),
newString;
for(var i = 0; i < wordsArray.length; i++){
if(!isNaN(parseFloat(wordsArray[i])) && isFinite(wordsArray[i])){
wordsArray[i] = "<span class='style'>" + wordsArray[i] + "</span>";
}
}
newString = wordsArray.join(' ');
element.innerHTML = newString;
I hope it helps you
UPD:
For all paragraphs https://jsfiddle.net/fazanaka/qx2ehym4/

Multiplication table in JavaScript returns undefined with multiplication number WHY?

Script part:
function makeTable() {
var num = document.getElementById('Numb').value;
var myPara = document.getElementById('para');
var tb = new Array();
for (var i = 1; i <= 10; ++i) {
var result = num * i;
tb.push(result);
tb[i] = tb[i] + "<br>";
}
tb = tb.join("");
myPara.innerHTML = tb;
}
HTML part
<input type = "number" value = "" id = "Numb" placeholder = "TABLE NUMBER">
<input type = "button" value = "Give me Table" onClick = "makeTable()">
<p align = "center" name = "myownpara" id = "para"> </p>
When I run this code it returns undefined with first element of array
Arrays start at 0, not 1. Change it to var i= 0 in your 'for' loop and add the line if(i==0) continue; right after starting your for loop to skip over 0.
Actually, another problem is your array. It might be best to initialise your 0th element because you are looking at it later. Change new Array() to new Array(""): To already add a 0th element so you dont have to when you use my aforementioned continue statement.
Update, refinement
I refined your code below. I don't know why you are using an array, as you want to output a string anyway. So Just add it to the string for every element as it reduces the amount of things you need to do. The below will work. I also removed you 'myPara' as you only use it once anyway, so theres no point in saving it.
Also note that in this case we don't need to start at 0 as we don't have an array to add to.
function makeTable() {
var num = document.getElementById('Numb').value;
// lets use a string since thats what you want in the end and its easier.
var tb = "";
for (var i = 1; i <= 10; ++i) {
// add it to the string. I reduced the number of steps as its so simple
// You don't need to save stuff in vars for this thing.
tb += (num * i) + "<br>";
}
document.getElementById('para') = tb;
}

how to split & add array values into different 'div' components without using "if" condition?

I am using HTML5 + javascript for developing a webpage. I have an array with 100 values. And i have a 10 different HTML5 "div" components. I'm adding 1st 10 array values into 1st "div", 2nd 10 array values into 2nd "div" and similarly goes on. I am using HTML DOM to add these array values into particular "div" component.
Here i have used "if...elseif" condition & is working fine.
But i'm asked not to use "if" condition to add array values into different 'div' elements. Is there any other possible methods to do this?
My div components are 'div1','div2'.......'div10'(added in body tag)
var myArray = ['user1', 'user2', 'user3', ..., 'user100'];
for(i=0;i<myArray.length;i++)
{
var a = document.createTextNode(myArray[i]);
if(i<=10)
{
var container1 = document.getElementById('div1');
container1.appendChild(a);
}
elseif(i>10 && i<=20)
{
var container2 = document.getElementById('div2');
container2.appendChild(a);
}
...
...
...
...
else
{
var container10 = document.getElementById('div10');
container10.appendChild(a);
}
}
It's bad solution. The better one is following:
for(j=0;j<10;j++)
{
//get div1, div2, div3 etc.
var container = document.getElementById('div'+(j+1));
for(i=0;i<10;i++)
{
//get proper value
var a = document.createTextNode(myArray[i+j*10]);
//insert value into container
container.appendChild(a);
}
}
var set=myArray.length/10; /** no of sets of 10 **/
for(i=0;i<set;i++){ //loop through sets
for(int j=(i*10);j<(i+1)*10;j++){ //loop through each set 0-9, 10-19
var a = document.createTextNode(myArray[j]);
document.getElementById('div'+(i+1)).appendChild(a);
}
}
var myArray = ['user1','user2','user3',...'user100'];
for(var i = 0; i < 10; i++) {
var container = document.getElementById("div" + (i + 1));
for(var j = 0; j < 10; j++) {
container.appendChild(document.createTextNode(myArray[(i * 10) + j]));
}
}
If you don't mind array values being inserted into each div as one text node, you could do:
var div, i;
for (i = 1; i < 11; ++i) {
div = document.getElementById('div' + i);
div.innerHTML = myArray.splice(0, 10).join(' ');
}
You don't need 2 for loops. Do you?
for (var i = 1; i <= 100; i++)
{
document.getElementById('div' + ( i%10 + 1)) //this will give your target div
}
P.S: spare me... Typing on mobile...

Categories

Resources