Having trouble with getElementsByTagName(blockquote) [closed] - javascript

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 6 years ago.
Improve this question
I am trying to get it to return "ha, awesome" followed by the index of the word "awesome"
HTML:
<blockquote id = "blocky">
ha, awesome<br>
</blockquote>
JS:
var x = document.getElementsByTagName(blockquote).innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName(blockquote).innerHTML = x + "<br>" + n;
If I change the JS to this, it works
var x = document.getElementById("blocky").innerHTML ;
var n = x.indexOf("awesome");
document.getElementById("blocky").innerHTML = x + "<br>" + n;
https://jsfiddle.net/mzrt/zaf98g8y/1/

First off, you need to pass it a string, not a variable (unless that variable contains a string).
var x = document.getElementsByTagName('blockquote');
Next, document.getElementsByTagName returns a element collection, not a single element. You can get the first result using [0].
var x = document.getElementsByTagName('blockquote')[0];
Or you can iterate through all of the elements using a for loop.
for (var i = 0; i < x.length; i++) {
var element = x[i];
element.innerHTML = '...';
}

Basically getElementsByTagName will return a node list, an array like object, you cannot access the property of a node from it directly, you have to use bracket notation to fetch the first node from it and then you can treat it as a node object,
var x = document.getElementsByTagName('blockquote')[0].innerHTML;
Since the element that you are targeting is an element with id, It is better to go with getElementById.

var x = document.getElementsByTagName('blockquote')[0].innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName('blockquote')[0].innerHTML = x + "<br>" + n;
Get element by tag name returns a node list, so you have to tell whitch node you do want.
Also you should pass tagname between single quotes.

Related

How can I print a js array into a div in html? [closed]

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 2 years ago.
Improve this question
Why I cant display elements that I push into an array, into an html div. Im just trying to print the word hello 3 times, but it does not work. When I print the array into the console the array does show the 3 Hello's.
$(function() {
var $buttonsArray = [];
var $buttondiv = $('#btndiv');
for (var i = 0; i < 3; i++) {
var $button = "hello";
$buttonsArray.push($button);
}
for (var j = 0; j < $buttonsArray.length; j++) {
$buttondiv.append($buttonsArray[j]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="btndiv"></div>
HTML is mainly text (or call it a string) and javascript variables can be string, number, objects, arrays.
By default, on all those javascript types, if you just place them into a DOM elements, the browser will attempt to convert them to string.
const someNumber = 1
const someString = 'hello'
const someObject = {answer:42}
const someArray = [1, 'help', 3, {a:2}]
document.write(someNumber + '<br/ >')
document.write(someString + '<br/ >')
document.write(someObject + '<br/ >')
document.write(someArray + '<br/ >')
// is the same as
document.write(someNumber.toString() + '<br/ >')
document.write(someString.toString() + '<br/ >')
document.write(someObject.toString() + '<br/ >')
document.write(someArray.toString() + '<br/ >')
When you deal with an array, you can use .join to regroup them
for example
const greets = ['allo', 'hello', 'holla'];
function render() {
// This write the list separated with comas using join
document.getElementById('app').innerHTML = greets.join(', ');
// This works too but can be slow and doesn't not allow much flexibility
document.getElementById('debug').innerHTML = JSON.stringify(greets);
}
render();
setTimeout(() => {
greets.push('oi');
render();
}, 1000)
<div id="app"></div>
<pre id="debug"></pre>

Unexpected behaviour with for in a nodelist [closed]

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 3 years ago.
Improve this question
I have a nodelist with 30 divs and I need to include 1 div every 4 divs but the var 'c' does not change and stack all the divs in the position[6].
for (i = 0; i < 8; i++) {
var pub = "pub-retangulo-";
var c = 2;
c += 4;
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
}
You are redeclaring your c variable at each iteration. That is why is it stuck at 6. You need to move this assignation outside your loop
var pub = "pub-retangulo-";
var c = 2;
for (i = 0; i < 8; i++) {
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
c += 4;
}
I've also moved your c+=4 at the end of the loop, this will cause the loop to execute at c = 2 the first time rather than c = 6
As Barmar said, you might not need a variable at all in this case. You are incrementing by four each time, so you could replace your c variable with 2 (initial value) + i(current iteration index) * 4 (increment ratio).
P.S. This code is UNTESTED, please don't just copy and paste it expecting everything to work perfectly. Try to understand it and apply it to your own context.

What does this code means? (Javascript FOR loop) [closed]

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 7 years ago.
Improve this question
Can someone explain this code to me?
Any help will be appreciated ! Thanks!!
<p id="arrayString"></p>
<script type="text/javascript">
var arrayString = "";
var myArray = ["pizza", "hamburger", "chicken leg"];
for (var i = 0; i < myArray.length; i++){
arrayString = arrayString + myArray[i] + " ";
}
document.getElementById("arrayString").innerHTML = arrayString;
</script>
</body>
Here is the code with some comment:
<p id="arrayString"></p>
<script type="text/javascript">
var arrayString = ""; //store an empty string in the variable (the purpose is to initialize the variable in wich after(for loop) we will store the names)
var myArray = ["pizza", "hamburger", "chicken leg"]; //create an array with some string elements
//foreach element in the array (the strings)...
for (var i = 0; i < myArray.length; i++){
//...add the 'i-est' element of the array to the string variable 'arrayString' and insert a space after the element
arrayString = arrayString + myArray[i] + " ";
}
//print the string in the html element with id 'arrayString'
document.getElementById("arrayString").innerHTML = arrayString;
</script>
</body>
The for statement iterates over the elements of the array, and in each iteration you access an element with: myArray[i]
Check here to see how the for loop works
I'm assuming you mean the for loop and not the other stuff.
for loops are basically while except more organized. for(var i = 0; is making the variable that is going to determine when to end the for loop.
i < myArray.length; is basically while(i < myArray.length) aka while i is less than myArray length it will do what's inside.
lastly, i++; tells the for loop what to do to i at the end of the statement to eventually make it >= to myArray.length.
The for loop creates a variable i and executes the code within the loop as long as i is less than the length of myArray. Each time the code in the loop is executed, i is increased by 1.
for (var i = 0; i < myArray.length; i++) {
arrayString = arrayString + myArray[i] + " ";
}
is saying for the variable i, if i < myArray.length, execute the code arrayString = arrayString + myArray[i] + " "; which adds the ith element of myArray to arrayString. For example, when the loop starts, i=0. So if it is true that i < myArray.length, then the 0th, or first, element of myArray is added to arrayString (Since array indexing begins at 0: 0 is the first element, 1 is the second, 2 is third, and so on. Then, once that is finished, the flow of control jumps back into the conditions in the for loop and executes i++, or "increase i by one". This whole process continues until the statement i < myArray.length is false (meaning i >= myArray.length, in which case the code in the for loop will be trying to add elements of the array that do not exist, like "add the 6th element of a 5 item long list").
The last line,
document.getElementById("arrayString").innerHTML = arrayString;
gets the element in the document with the id "arrayString" and displays the text contained in arrayString in that element (which is the one defined at the top in paragraph tags).
It's converting an array into a string. You could just use this, though:
document.getElementById("arrayString").innerHTML = myArray.join(' ');

JavaScript array push not working [closed]

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 7 years ago.
Improve this question
I am trying to push a value into an array and it is giving me this error in the developer tools.
Uncaught TypeError: Cannot read property 'push' of null
Here is the code that it seems to be sticking on, word and local word were defined earlier like this.
var word = [];
var localWord = [];
function setLocalArray() {
// first get words from text field and update word array.
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
localStorage.setItem("localWord",JSON.stringify(localWord));
text2Array();
reveal();
}
localWord.push(key2); Seems to be what it is getting stuck on. I have looked at everything I can find on the push method and I can't seem to find why it is giving me this error. Help?
Here is the full code at jsfiddle http://jsfiddle.net/runningman24/jnLtpb6y/
Try this...
var localWord = new Array(); //create new array
var word = new Array();
function setLocalArray() {
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
}
I found the problem, if you look in the jsfiddle I posted I am trying to pull localWord from localStorage even though it doesn't exist and so it sets it to null. Thank you to all for the ideas and contributions.
You could try isolating the scope of your variable using the module pattern:
var arrayManager = (function () {
var word = [];
var localWord = [];
function setLocalArray() {
// first get words from text field and update word array.
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
localStorage.setItem("localWord",JSON.stringify(localWord));
text2Array();
reveal();
}
return {
setLocalArray:setLocalArray
} ;
}());
and the from the outside you have to simply call arrayManager.setLocalArray()

Append to an array made from ul [closed]

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
Hi im trying to append a "s" to each element an array created from a unsorted list. Here is my code and I am not sure what I am doing wrong.
Html:
<ul>
<li class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="fruit">Pineapple</li>
<li class="fruit">Orange</li>
</ul>
Javascript to append s to each element
var list = document.getElementByClassName('friut');
for(var i=0;i < list.length; i++) {
var arrValue = list[i];
list[i] = arrValue.innerHTML + 's';
}
First, you misspelled both getElementsByClassName and "fruit". If all you are trying to do is make an array of strings equal to the list elements' values + "s", that's your problem.
If you're trying to actually add 's's to the HTML, you want something like this:
for(var i=0;i < list.length; i++) {
list[i].innerHTML += 's';
}
It's getElementsbyClassName, not getElementByClassName. You also spelled 'fruit' as 'friut'
var list = document.getElementsByClassName('fruit');
for(var i=0;i < list.length; i++) {
var arrValue = list[i];
list[i] = arrValue.innerHTML + 's';
}

Categories