Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I want to make an element 50 times within a for loop. My code is below:
function pGenerate() {
for (i, i <= 50; i++;) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
The expected result is that it generates 50 <p> tags with "sample content inside of them. The actual result is well...nothing. https://jsfiddle.net/2L8reked/1/
My thought process behind the code I wrote this code is as follows: I basically have a loop set to cycle 50 times. for each cycle, I want to create a p tag, along with create a text node with the content "sample paragraph." In the next step, I grab the div by it's id, #content, and I then attempt to populate the area using insertBefore.
My error here seems to be how I use insertBefore. Looking this up on MDN, it's definition is "inserts the specified node before the reference node as a child of the current node." https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
With that definition in mind - I'm using this with the understanding as of now that I'm inserting (or attempting to) the p tags as a child of #content. Should I be using a different method? Am I misunderstanding how this works?
I also tried an innerHTML approach, seen here: https://jsfiddle.net/0e1ej9sk/1/
which method is best suited for what I'm trying to do?
In the first example what is the flaw behind my logic of the use of insertBefore?
You have 3 syntax errors.
Change i, in for loop to 1=1; then remove the last ; where i++; to i++
function pGenerate() {
for (i=1; i <= 50; i++) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
window.onload = function() {
pGenerate();
}
<div id="content"></div>
You need to initialize i at 1, and properly separate all parts of the for statement with semi-colons, like this:
function pGenerate() {
for (var i = 1; i <= 50; i++) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph (i=" + i + ")");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
pGenerate();
<div id="content"></div>
you can do this
function pGenerate() {
for (i=1; i <= 50; i++) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
document.ready(pGenerate);
Related
This question already has answers here:
What's the best way to loop through a set of elements in JavaScript?
(14 answers)
Closed 1 year ago.
I'm using the code below, written by Niels Reijnders on this thread Wrap each line of paragraph in a span to wrap each line of a paragraph in span.
function splitLines(container, opentag, closingtag) {
var spans = container.children,
top = 0,
tmp = '';
container.innerHTML = container.textContent.replace(/\S+/g, '<n>$&</n>');
for (let i = 0; i < spans.length; i++) {
var rect = spans[i].getBoundingClientRect().top;
if (top < rect) tmp += closingtag + opentag;
top = rect;
tmp += spans[i].textContent + ' ';
}
container.innerHTML = tmp += closingtag;
}
splitLines(document.querySelectorAll('p')[0], '<span>', '</span>')
It works great and accomplishes what I needed, but only selects the first paragraph of the DOM, not the others. It seems like adding forEach method might solve what I'm looking for, but I don't know how to implement it within this code.
Any help would be very appreciated.
Thanks
You would want something like:
document.querySelectorAll('p').forEach(p => splitLines(p, '<span>','</span>'))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am creating an HTML document and using javascript to create an image element.
Here is my code (create is already defined):
create=document.createElement("img");
create.src = 'data/1.png';
create.alt = 'image1';
create.style.magin = '1px';
eval("create.id = 'image" + count + "'");
create.class = 'block'; // line that breaks the code
document.body.appendChild(create);
I don't know what's going wrong here, but it's probably something obvious. Does anyone have any ideas?
Here's your code working with the variable count defined, an example image and the correct way to add a class to the element:
var count = 1;
create=document.createElement("img");
create.src = 'http://via.placeholder.com/350x150'; // 'data/1.png';
create.alt = 'image1';
create.style.magin = '1px';
eval("create.id = 'image" + count + "'");
create.classList.add('block');
document.body.appendChild(create);
As no necessity for eval and you can use classList for add a class.
for(var count = 1; count < 10; count++){
create=document.createElement("img");
create.src = 'data/1.png';
create.alt = 'image' + count;
create.style.magin = '1px';
create.id = 'image' + count;
create.classList.add('block');
document.body.appendChild(create);
}
You also can use create.style.display = 'block'; if you want just add a style.
More examples how set attributes and styles here
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm afraid it might be a silly question, but I have no idea what occurs my problem.
I dynamically create buttons (each button has unique id), and I store each btn reference (document.getElementById()) in simple two-dimensional array. All these because i need to hold btns in well organized structure.
The problem is: when i try to modify element by reference previously stored in my array, there appears to be no connection between ref and html element.
var Table = {
size: 10,
table: [],
generateTable: function() {
var i = 0,
j = 0,
id = null,
tablePlaceholder = document.getElementById("tableHTML");
//Generate table
for (i = 0; i < this.size; i++) {
this.table.push([]);
for (j = 0; j < this.size; j++) {
id = i.toString() + "-" + j.toString();
tablePlaceholder.innerHTML += element(id);
this.table[i].push(document.getElementById(id));
}
tablePlaceholder.innerHTML += "</br>";
}
console.log(this.table[0][0].className);
document.getElementById("0-0").className += " btn-success";
console.log(this.table[0][0].className);
}, ...
Results of last two console.logs is the same, but element has changed in DOM.
table[0][0] returns same content as document.getElementById("0-0").
(element() function returns simple html code (it works well))
innerHTML += '<div>...</div>';
This could break references to already constructed DOM elements and cause other chaos. In reality, all you want to do is append a single new element to the end.
var elem = document.createElement('div');
elem.id = id;
tablePlaceholder.appendChild(elem);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm fairly new to Javascript and I'm trying to achieve something extremely simple but it seems impossible (at least the way I want it). Basically, I've got a HTML file with an image that I want to change to a different one every time I click on a button. I've got 4 images in total and the initial image in the HTML file is "1.jpg". The problem is, I can only change the initial "1.jpg" to "2.jpg" and any further attempts to change "2.jpg" to "3.jpg" and so on fail.
Here's the code
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
if (document.getElementById('img1').src=a[0])
{
document.getElementById('img1').src=a[1];
}
else if (document.getElementById('img1').src=a[1])
{
document.getElementById('img1').src=a[2];
}
else if (document.getElementById('img1').src=a[2])
{
document.getElementById('img1').src=a[3];
}
else
{
document.getElementById('img1').src=a[0];
}
}
The thing is, I can get it to work if I change the code to:
var i=0;
function changepicture() {
i++;
if (i>3) { i=0; }
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
document.getElementById('img1').src=a[i];
}
But, in spite of having a working alternative, I'm still not satisfied as I am convinced the first method should also work.
It appears you're using = where you mean to use == or ===.
Edit: To be more clear, I mean in the parenthesis of the if statements themselves, like this:
if (document.getElementById('img1').src == a[0]) {
Double edit: I believe I found another issue. It's in the logic of the if statements:
document.getElementById('img1').src
Doesn't just equal what's in the html, like '1.jpg'. It returns the WHOLE url. Check out the console logs on this quick fiddle I made: http://jsfiddle.net/71t4axv0/1/
First, it'll complain about that image not really being an image. Then you can see the actual logic: 'http://fiddle.jshell.net/_display/2.jpg', of course, does not equal 2.jpg
if (document.getElementById('img1').src=a[0]) {
document.getElementById('img1').src=a[1];
}
This particular statement of must have == instead of =.
The = / == typo that has been addressed by the other answers. Here, I'll address the second version of the function, where it seems you attempted to implement it as a loop. You'd have to write it like this:
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
var element = document.getElementById('img1');
var src = element.src.split('/').pop(); // get filename
for(var i = 0; i < 3; i++) {
if (src == a[i]) {
element.src = a[i + 1];
return; // stop evaluating now
}
}
element.src = a[0];
}
Note: as a work around to the issue that holl pointed out about using the .src property, I use .src.split('/').pop() to get just the filename. This works, but an alternate solution would be to use the full paths in your array instead.
If you prefer, you can simplify this by using the indexOf method and the % operator:
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
var element = document.getElementById('img1');
var curIndex = a.indexOf(element.src.split('/').pop());
element.src = a[(curIndex + 1) % a.length];
}
Here's a modified snippet that demonstrates the basic behavior (just with text, not images):
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
var element = document.getElementById('demo');
var curIndex = a.indexOf(element.innerText);
element.innerText = a[(curIndex + 1) % a.length];
}
#demo { width: 40px; height: 40px; border: 1px solid #000; margin: 5px }
<div id="demo">1.jpg</div>
<button onclick="changepicture()">change</button>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I feel like there is too much repetitive code going on here. All I am doing is doing a basic regex match for a string in the URL. If a match is found, I find an li with a class (.index, .grid, .type) and add the active class. This is just for my main nav in an attempt to make it some what dynamic. However, I feel like there is a more efficient way to code this. Any help is greatly appreciated.
$( document ).ready(function() {
var myLocation = window.location;
var convertURL = new String(myLocation);
var index = /index/i;
var grid = /grid/i;
var type = /type/i;
var urlIndex = convertURL.match(index);
var urlGrid = convertURL.match(grid);
var urlType = convertURL.match(type);
if(urlIndex) {
$('.index').addClass('active');
}else if(urlGrid) {
$('.grid').addClass('active');
}else if(urlType) {
$('.type').addClass('active');
}
});
$(function(){
["index", "grid", "type"].forEach(function(term){
if(new RegExp(term, "i").test(location.href))
$("." + term).addClass("active");
});
});
$(document).ready(function () {
// use single var per function, good for minimizing and other stuff
var
i,
// new string literal, not String object
convertURL = '' + window.location,
// the array of strings keeps only the difference from the repetitive code
classes = ['index', 'grid', 'type'],
// using functions with proper arguments reduces repetitivness
matches = function (regex) {
return convertURL.match(new RegExp(regex, 'i'));
}
// var
;
// always use += instead of ++ -> makes for clear intention
for (i = 0; i < classes.length; i += 1) {
if (matches(classes[i])) {
// returning out of this function stops iteration
return $('.' + classes[i]).addClass('active');
}
}
});