Issue on Processing Array Items Into a Div - javascript

can you please take a look at this code and let me know why I am not able to add the array Items into the .box? I already used the .text() and .html()
var letters = [];
var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
var letters = str.split(",");
for (var j = 0; j <letters.length; j++) {
$(".box").html(letters[j]);
}
but they only add the last item "Z" into the box

You need to use .append() because .html() will replace the whole html everytime

Because you're using .html() which replaces any pre-existing text with the new text.
Use .append() instead:
$(".box").append(letters[j]);

.html() will replace the content at the each iteration of loop. In first iteration 'A' will be placed into (".box") and int second iteration 'B' will be replaced by 'A' and so on. When loop ends the last letter 'Z' will be the only content in ('.box'). if youy want to add all letters in ('.box') use .append()
see link : http://api.jquery.com/append/

That's because html doesn't append but replaces the content.
A solution could be to use append instead of html but that's slow if you have a big array. In such a case, the best practice is to build the HTML in one go :
$(".box").html(letters.join(''));
If what you want is to have a delay between the box being changed, you can use setTimeout :
(function step(){
var letter = letters.shift();
if (!letter) return;
$('.box').html(letter)
setTimeout(step,200);
})()

You will need a delay in updating the box in order to show the letters one after the other:
var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
var letters = str.split(",");
next();
function next() {
if( letters && letters.length) {
$(".box").text(letters.shift());
window.setTimeout(next, 500);
}
}

Related

getElementsByClassName isn't returning all elements

I'm creating a button that I should highlight certain words within a specified class, but I am having issues with it returning all elements within the class. It will only work if I specify an index, so I'm assuming there may be something wrong with the existing "for loop". Any help is appreciated!
This will work, but only "highlights" the first element in the class, of course:
var bodyText = document.getElementsByClassName('test')[0].innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag,
highlightEndTag);}
document.getElementsByClassName('test')[0].innerHTML = bodyText;
return true;
This will not work at all:
var bodyText = document.getElementsByClassName('test').innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag,
highlightEndTag);}
document.getElementsByClassName('test').innerHTML = bodyText;
return true;
If you want to replace multiple words in multiple elements, you need two loops:
const testElements = document.getElementsByClassName('test');
for (const element of testElements) {
for (const search of searchArray) {
element.innerHTML = doHighlight(element.innerHTML, search, highlightStartTag, highlightEndTag);
}
}
As you can see getElementsByClassName is pluralized (Elements). Indeed a same class can be assigned to multiple HTML elements. You won't find any way to ommit the [0] and you shouldn't anyway as it might mean you're getting data from the wrong node. If you need data from a specific element that you can ensure is unique then you need to give it an id and use getElementById instead.
You cannot access innerHTML in something which returns an htmlcollection
document.getElementsByClassName('test').innerHTML
Because it's written in plain english: getElementsByClassName. plural.
"Elements".
with an "s" at the end...
meaning it's a (sort of) Array (an htmlcollection)

JS: I can't get the inner HTML of elements with a specific class name

I'm trying to create a calculator out of javascript to work on my skills. I've added the class num to all of my buttons that have a number.
I'm trying to display to display the innerHTML of those buttons in the console when I click them with this code:
var num = document.getElementsByClassName('num');
num.addEventListener('click', getNum);
function getNum(){
console.log(num.innerHTML);
}
getNum();
However all I get is
num.addEventListener is not a function.
Here is my codepen: https://codepen.io/teenicarus/pen/wrEzwd
what could I be doing wrong?
You need to change the code like below. getElementsByClassName returns collection of elements. Loop through the elements and add click event listener. In getNum, you can use this to get access to the button clicked.
var num = document.getElementsByClassName('num');
for (var i = 0; i < num.length; i++) {
num[i].addEventListener('click', getNum);
}
function getNum(){
console.log(this.innerHTML);
}
You can also use Array forEach like the following:
[].forEach.call(num, function(el){
el.addEventListener('click', getNum);
})
getElementsByClassName returns a collection of elements, not a single element. If you want to get single element assign it an id attribute and use getElementById. This way you can use addEventListener function
Here's a solution you can plug directly in your codepen:
var nums = document.getElementsByClassName('num');
[].forEach.call(nums, num => num.addEventListener('click', numClick));
function numClick(){
// adding + turns the text into an actual number
console.log(+this.innerHTML);
}
getElementsByClassName() returns an HTMLCollection, to iterate over it you can pass it to [].forEach.call() like I showed above.
I also renamed the handler to numClick, since it doesn't "get" the number. And added +, which is a nice shortcut to turn text into a number (otherwise, adding two numbers would yield unexpected results, like "1" + "2" => "12"
The .getElementsByClassName returns not an element, but a collection of them.
You can access elements using .getElementsByClassName(num)[element's sequential number], or better use id's and getElementById method.
Here is the modified code for your desired output.just copy and try:
var num = document.getElementsByClassName('num');
//num.addEventListener('click', getNum);
for (var i = 0; i < num.length; i++) {
num[i].addEventListener('click', getNum);
}
function getNum(){
document.getElementById('result').innerHTML+=this.innerHTML;
console.log('value:'+this.innerHTML);
}
//getNum();
As you tagged Jquery to your question I suppose that you are able to use Jquery as well. You can grab the clicked element's class and referance it with 'this' to get its text.
$('.num').click(function(){
var x = $(this).text();
console.log(x);
});
This is a working example you can check the console.log DEMO

JavaScript regex to match items in a stringified array that don't contain a search term

I want to remove all span items that don't contain the string 'foo' from a stringified array. The string looks like this:
["<span>This is some text</span>","<span>This is more foo</span>","
<span><span>Inner span blah</span>This is one has an inner span
foo</span>","<span>Last one</span>"]
The end result string should look like this:
["<span>This is more foo</span>","<span><span>Inner span blah</span>
This is one has an inner span foo</span>"]
Creating an array with JSON.parse() and then filtering works, but it isn't fast enough for my purposes.
I've tried regular expression variants with negative lookahead, but can't seem to get them to work.
JavaScript provide functions to achieve what you want, using a regex will spare unnecessary resources.
Code:
var myArray = ["<span>This is some text</span>","<span>This is more foo</span>","<span><span>Inner span blah</span>This is one has an inner span foo</span>","<span>Last one</span>"];
for (i=0;i<myArray.length;++i) {
if(myArray[i].indexOf("foo") === -1){
myArray.splice([i], 1);
}
};
console.log(myArray);
Outputs:
["<span>This is more foo</span>", "<span><span>Inner span b...n inner span foo</span>"]
CODEPEN DEMO
Explanation :
Loop myArray:
for (i=0;i<myArray.length;++i)
Check if foo isn't present using indexOf
if(myArray[i].indexOf("foo") === -1)
If foo isn't present, remove it from array using splice
myArray.splice([i], 1);
You could try something like.
var array = ["<span>This is some text</span>","<span>This is more foo</span>","
<span><span>Inner span blah</span>This is one has an inner span
foo</span>","<span>Last one</span>"];
for (var item in array) {
var value = array[item];
if(value.indexOf('foo') < 0) {
array.splice(item, 1)
}
}
Explanation:
First you initialise the an array with all your strings.
Using a for in loop you iterate over that array.
And every time you find the word foo you remove the current element from the array.

Find occurrences of a string in a given element.

I am looking for a way to find instances of a certain character within a certain element. I am aware of doing something like:
var string = 'this is a string';
string.indexOf('a');
however, i want indexOf to look at a particular tag within a particular html file. (in this case, p tags). I have commented out what i tried to use in order to achieve this.
function findQuestion() {
// var string1 = document.getElementsByTagName('p');
var string2 = '??';
if (string2.indexOf('?') !== -1) {
console.log('foundQuestion');
}
else {
console.log('nothing');
}
}
findQuestion();
This code obviously just checks to see that there is a '?' in string2, but how do i write this to find all instances of '?' within p tags and return all content preceding that up to the opening p tag in which the '?' was found?
thanks.
How you could do that:
Get all p elements.
Create an empty array, results
Iterate over them and check for each p element
If the p's innerHTML contains a question mark split the string at the question mark, get the first part and add a question mark. Then add this new string to the results array
Return the results array
Example Code:
function findQuestion() {
var ps = document.getElementsByTagName('p');
var result = [];
for(var i = 0; i < ps.length; i++){
var p = ps[i];
if (p.innerHTML.indexOf('?') !== -1) {
result.push(p.innerHTML.split("?")[0] + "?");
}
}
return result;
}
findQuestion();
http://jsfiddle.net/3o4tcchL/1/
Use a loop condition to check the entirety of the content within , after that use something like slice, which will grab everything up to a particular index you specify.

GetElementByID - Multiple IDs

doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));
This doesn't work, so do I need a comma or semi-colon to make this work?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You have several different options:
You could implement your own function that takes multiple ids and returns multiple elements.
You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string .
You could put a common class names on all those nodes and use document.getElementsByClassName() with a single class name.
Examples of each option:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
or:
// put a common class on each object
doStuff(document.getElementsByClassName("circles"));
or:
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));
This will not work, getElementById will query only one element by time.
You can use document.querySelectorAll("#myCircle1, #myCircle2") for querying more then one element.
ES6 or newer
With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.
Example:
const elementsList = document.querySelectorAll("#myCircle1, #myCircle2");
const elementsArray = [...elementsList];
// Now you can use cool array prototypes
elementsArray.forEach(element => {
console.log(element);
});
How to query a list of IDs in ES6
Another easy way if you have an array of IDs is to use the language to build your query, example:
const ids = ['myCircle1', 'myCircle2', 'myCircle3'];
const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
No, it won't work.
document.getElementById() method accepts only one argument.
However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll() method:
document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");
I suggest using ES5 array methods:
["myCircle1","myCircle2","myCircle3","myCircle4"] // Array of IDs
.map(document.getElementById, document) // Array of elements
.forEach(doStuff);
Then doStuff will be called once for each element, and will receive 3 arguments: the element, the index of the element inside the array of elements, and the array of elements.
getElementByID is exactly that - get an element by id.
Maybe you want to give those elements a circle class and getElementsByClassName
document.getElementById() only takes one argument. You can give them a class name and use getElementsByClassName() .
Dunno if something like this works in js, in PHP and Python which i use quite often it is possible.
Maybe just use for loop like:
function doStuff(){
for(i=1; i<=4; i++){
var i = document.getElementById("myCiricle"+i);
}
}
Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.
<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>
<script>
document.getElementById('click').addEventListener('click', function(){
doStuff();
});
function doStuff() {
for(var i=1; i<=2; i++){
var el = document.getElementById("hello" + i);
el.style.display = 'none';
}
}
</script>
Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.
The best way to do it, is to define a function, and pass it a parameter of the ID's name that you want to grab from the DOM, then every time you want to grab an ID and store it inside an array, then you can call the function
<p id="testing">Demo test!</p>
function grabbingId(element){
var storeId = document.getElementById(element);
return storeId;
}
grabbingId("testing").syle.color = "red";
You can use something like this whit array and for loop.
<p id='fisrt'>??????</p>
<p id='second'>??????</p>
<p id='third'>??????</p>
<p id='forth'>??????</p>
<p id='fifth'>??????</p>
<button id="change" onclick="changeColor()">color red</button>
<script>
var ids = ['fisrt','second','third','forth','fifth'];
function changeColor() {
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).style.color='red';
}
}
</script>
For me worked flawles something like this
doStuff(
document.getElementById("myCircle1") ,
document.getElementById("myCircle2") ,
document.getElementById("myCircle3") ,
document.getElementById("myCircle4")
);
Use jQuery or similar to get access to the collection of elements in only one sentence. Of course, you need to put something like this in your html's "head" section:
<script type='text/javascript' src='url/to/my/jquery.1.xx.yy.js' ...>
So here is the magic:
.- First of all let's supose that you have some divs with IDs as you wrote, i.e.,
...some html...
<div id='MyCircle1'>some_inner_html_tags</div>
...more html...
<div id='MyCircle2'>more_html_tags_here</div>
...blabla...
<div id='MyCircleN'>more_and_more_tags_again</div>
...zzz...
.- With this 'spell' jQuery will return a collection of objects representing all div elements with IDs containing the entire string "myCircle" anywhere:
$("div[id*='myCircle']")
This is all! Note that you get rid of details like the numeric suffix, that you can manipulate all the divs in a single sentence, animate them... Voilá!
$("div[id*='myCircle']").addClass("myCircleDivClass").hide().fadeIn(1000);
Prove this in your browser's script console (press F12) right now!
As stated by jfriend00,
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes.
However, here's some example code I created which you can give one or a comma separated list of id's. It will give you one or many elements in an array. If there are any errors, it will return an array with an Error as the only entry.
function safelyGetElementsByIds(ids){
if(typeof ids !== 'string') return new Error('ids must be a comma seperated string of ids or a single id string');
ids = ids.split(",");
let elements = [];
for(let i=0, len = ids.length; i<len; i++){
const currId = ids[i];
const currElement = (document.getElementById(currId) || new Error(currId + ' is not an HTML Element'));
if(currElement instanceof Error) return [currElement];
elements.push(currElement);
};
return elements;
}
safelyGetElementsByIds('realId1'); //returns [<HTML Element>]
safelyGetElementsByIds('fakeId1'); //returns [Error : fakeId1 is not an HTML Element]
safelyGetElementsByIds('realId1', 'realId2', 'realId3'); //returns [<HTML Element>,<HTML Element>,<HTML Element>]
safelyGetElementsByIds('realId1', 'realId2', 'fakeId3'); //returns [Error : fakeId3 is not an HTML Element]
If, like me, you want to create an or-like construction, where either of the elements is available on the page, you could use querySelector. querySelector tries locating the first id in the list, and if it can't be found continues to the next until it finds an element.
The difference with querySelectorAll is that it only finds a single element, so looping is not necessary.
document.querySelector('#myCircle1, #myCircle2, #myCircle3, #myCircle4');
here is the solution
if (
document.getElementById('73536573').value != '' &&
document.getElementById('1081743273').value != '' &&
document.getElementById('357118391').value != '' &&
document.getElementById('1238321094').value != '' &&
document.getElementById('1118122010').value != ''
) {
code
}
You can do it with document.getElementByID Here is how.
function dostuff (var here) {
if(add statment here) {
document.getElementById('First ID'));
document.getElementById('Second ID'));
}
}
There you go! xD

Categories

Resources