javascript getElementById function not working - javascript

I tried the following: it is working fine
function saveTitle(index,id){
arrtitle[1] = document.getElementById("title_1").value;
arrtitle[2] = document.getElementById("title_2").value;
arrtitle[3] = document.getElementById("title_3").value;
}
but as I tried the following:
function saveTitle(index,id){
for(i=1;i<=count;i++)
arrtitle[i] = document.getElementById("title_"+i).value;
}
It gives me an error that : Uncaught TypeError: Cannot read property 'value' of null
Please suggest me something. Thanks...

You can use querySelectorAll to get all the elements that contains "title_" string . See the bellow code.
function getTitles() {
var arrtitle = [];
var elements = document.querySelectorAll("*[id*='title_']");
for (i = 0; i < elements.length; i++) {
var titleId = elements[i].id.replace("title_", "");
arrtitle[titleId] = elements[i].value;
}
return arrtitle;
}
getTitles();

Based on what you've posted, if that's your actual code, the only possibility seems to be that count is higher than the maximum element that exists (or there's a hole). For example, count might be 4, and there is no element with the id of title_4.
The javascript debugger would help you find this pretty easily.
I'd also suggest using braces around the body of your for loop, which would significantly help readability.

Related

Error code "Uncaught TypeError: Cannot read property 'style' of null" in my javascript code

I am using a for(){} statement to loop through every element I have in order to change the text color and remove underlining when a function is called. After doing so, the function will then set the font color and underline the selected text. However, I keep receiving the error message Uncaught TypeError: Cannot read property 'style' of null. I triple-checked My element's names, making sure that they were right. They were.
let videos = ["video 1","video 2"];
let current_video = undefined;
window.onload = function () {
function update_video(video) {
// loops through all of my h2 elements to change their style to default
for(var i = -1 ; i < videos.length ; i++) {
document.getElementById(String("vid-"+i)).style.color = "#ca6735";
document.getElementById(String("vid-"+i)).style.textDecoration = "none";
}
// sets the selected h2 element (using a button to select it) to a new color with an underline.
current_video = Number(video);
document.getElementById(String("vid-"+video)).style.color = "#49a1b6";
document.getElementById(String("vid-"+video)).style.textDecoration = "underline";
}
document.getElementById("vid-bt-0").addEventListener("click", function() {
update_video(0);
});
document.getElementById("vid-bt-1").addEventListener("click", function() {
update_video(1);
});
}
The code above is what I have currently. The code underneath the second comment works.
I guess because of i = -1 in for loop the problem occurs:
So, try with the below code:
for(var i = 0; i < videos.length ; i++) {
document.getElementById(String("vid-"+i)).style.color = "#ca6735";
document.getElementById(String("vid-"+i)).style.textDecoration = "none";
}
The first thing I notice here is that your for loop starts at -1; so the first video is should be vid--1. Is that correct? If not, just make your loop start from 0 and not from -1.
If that's not the issue, try to console.log your strings such that you understand which is the problematic one.
Perhaps this is happening because you start the loop from i = -1?
Also, no need to use :
String("vid-"+i)
this will do the same:
"vid-" + i;

Can't search array by indexOf()

I tried to put a series of DOM elements having the same class inside an array, and then try to find what index is one of them located by using .indexof(). However, it seems like it is not working. Did I wrote anything wrong? Or there should be other ways that I can find an index of an element in a array?
Here is a little piece of code
window.onload = function(){
var addBtn = document.querySelectorAll(".add");
for(var i = 0; i < addBtn.length; i++){
addBtn[i].onclick = addTime;
}
};
function addTime(){
var update = parseInt(this.parentElement.getElementsByTagName("SPAN")[0].innerHTML) + 1;
var digits = this.parentElement.parentElement.querySelectorAll(".digit");
if(digits.indexOf(this.parentElement) % 2){ //Uncaught TypeError: digits.indexOf is not a function
}else{
carryOn(this, update);
}
}
It just keep telling me that "Uncaught TypeError: digits.indexOf is not a function".
querySelectorAll return a NodeList, it's an array-like object, not an actual array. It does not have an indexOf methods.
You can:
cast array method on an array-like by Array.prototype.indexOf.call(digits, ....).
produce a real array by Array.from(digits).

how to remove HTML tags from a string in JavaScript without using regexp?

I am new to programming and I was solving this exercise.
I have tried 3 loops with string.slice() but for some reason it prints an empty string.
Would you please explain what happens inside my code and why it prints the wrong output and how I can correct, rather than giving me your version of the correct answer, so that I can learn from my mistakes.
the test input is
<p><strong><em>PHP Exercises</em></strong></p>
and output should be PHP Exercises
p.s this is not a PHP exercise, I'm not confused
here is my code :
function remove(answer){
var sen = answer.split("");
var arr = [];
for (var i = 0; i<answer.length; i++){
if (answer[i] == "<"){
for (var j = i; j<answer.length; j++){
if (answer[j] == ">"){
for (var k = j; k<answer.length; k++){
if (answer[k] == "<"){
return answer.slice(j+1, k);
}
}
}
}
}
}
}
Try this:
function stripTags(data)
{
var tmpElement = document.createElement("div");
tmpElement.innerHTML = data;
return tmpElement.textContent || tmpElement.innerText || "";
}
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
alert(stripTags(something));
or You can use string.js (string.js link):
var S = window.S;
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
something = S(something).stripTags().s;
alert(something);
<script src="https://raw.githubusercontent.com/jprichardson/string.js/master/dist/string.min.js"></script>
if You're trying nodejs so:
var S = require('string');
var something = '<p><strong><em>PHP Exercises</em></strong></p>';
something = S(something).stripTags().s;
console.log(something);
As to why the provided code isn't working, the code returns when j = 2 and k = 3. I discovered this by writing console.log(j, k); immediately before the return. This insight made it clear that the code is identifying the first set of open tags, when actually you seem to want to identify the open and closed "em" tags. The answers provided by others are more robust, but a quick fix to your code is:
change
if (answer[i] == "<"){
to
if (answer.slice(i, i+3) == "<em"){
Hope this helps!
Your code does not account for ... nothing. It simply stops at the first encounter of what's between ">" and "<", which is, in the first case, is nothing! You should check if a character is present, and move on if not.
Honestly, this is one of those useless exercises that text books use to try to get you to think outside the box. But you will never want to loop through a string to find text between tags. There are so many methods built in to JavaScript, it's literally reinventing the wheel to do this... that is if a wheel were really a for-loop.
If you really want to avoid Regex and other built in functions so that you can learn to problem solve the long way, well try slicing by brackets first!

while (line = readline())

I'm new to JavaScript and are trying to solve a problem. I shall only write in JavaScript and the instructions are telling me to use readline(), for example like this: while (line = readline())
But I cant get how this works and I cant find any information about this in JavaScript. I want to get a users input and then put that in a variable. But when I try "while (line = readline())" I can's se anything happen (like with propt, which is the only way I know)...
Thankful for your help!
Here is my code (which works if I use alert and prompt istead of print and readline):
var usersNumber;
while (usersNumber = readline()) {
if (1 <= usersNumber && usersNumber <= 1000000000)
{
var inputBinary = usersNumber.toString(2);
var binaryArray = [];
for (i = 0; i < inputBinary.length; i++) {
binaryArray[i] = inputBinary.charAt(i);
};
binaryArray.reverse();
var stringBinaryFromArray = "";
for (i = 0; i < binaryArray.length; i++) {
stringBinaryFromArray = stringBinaryFromArray + binaryArray[i];
}
var digit = parseInt(stringBinaryFromArray, 2);
print(digit);
}
}
readline() is not a standard Javascipt function. You can use prompt() instead
while (usersNumber = prompt())
You might need to change the input from a string to a number.
while (usersNumber = Number(prompt()))
On another note, there are built-in functions you can use instead of the loops you have. split() and join(). You can even do it all in 1 line.
var stringBinaryFromArray = inputBinary.split('').reverse().join('');
(line = readline()) both assign line AND returns the value returned by readline()
if readline() returns null, line is null and the loop stops

Function Creating Array of Spans Always Returns Undefined

I have a method which returns an array of spans of a given id pattern. This array does get created and all the proper elements appear to be in it when I test by print out the values of the array at the end of the function.
This is the function:
function getAllSpansForID(sectionID) {
var foundAllSpans = false,
i = 1,
spanID,
span,
spanArray = new Array();
/* Keep looking until we found all the selection spans.*/
while (!foundAllSpans) {
spanID = sectionID + "-" + i;
span = document.getElementById(spanID);
/*
If we didn't get a span we can assume there are no more to find.
We are done with this loop.
*/
if (span == null) {
foundAllSpans = true;
console.log("Found all spans.");
}
/*
Else, add the span to the array we are going to return.
*/
else {
spanArray[i-1] = span;
i++;
}
}
console.log("returning spanArray.length: " + spanArray.length);
for (i = 0; i < spanArray.length; i++) {
console.log("spanArray[i].id: " + spanArray[i].id);
console.log("spanArray[i].outerHTML: " + spanArray[i].outerHTML);
}
return spanArray;
}
My problem is that whenever I call this function the returned value is ALWAYS UNDEFINED.
This code:
var spansArray = getAllSpansForID(verseID),
length = spansArray.length;
always produces this error:
Uncaught ReferenceError: spansArrray is not defined
I have found many SIMILAR problems on SO with returnign arrays due to scoping problems but none to match my exact situation. I have tried altering this method, including using spanArray.push(span), and spanArray.push.apply(spanArray, span) to add my spans, but to no avail. I am out of ideas.
In the error message I can spot an r too much:
Uncaught ReferenceError: spansArrray is not defined
^^^
Seems to be another typo, not in the code you posted here but in the one you executed…
change to:
var spansArray = getAllSpansForID(verseID);
var length = spansArray.length;
D'OH!!
As you can see by my error message, spansArrray (3 r's) is undefined. I defined spansArray (2 r's). I fixed and all works well. Just a typo....
I did not lift length = spansArray.length; straight from the code but rather just wrote it out, so the code posted here would not have failed.
Sorry everyone. I appreciate all the help just the same!!!

Categories