getElementsByClassName not showing data in an element [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed last year.
I know there are a lot of questions regarding the getElementsByClassName not working, however I browsed through many and coudldnt find an answer for my situation.
Basically I have the following code:
<script>
var res = localStorage.getItem('img');
if(res == null){
const myList = ['๐Ÿ’', '๐Ÿ•', '๐Ÿˆ', '๐Ÿ…', '๐ŸŽ', '๐Ÿฆ“', '๐Ÿ„', '๐Ÿฆ’', '๐Ÿ˜', '๐Ÿฆ”', '๐Ÿฆ‰', '๐ŸŠ', '๐Ÿฆ–', '๐Ÿฌ', '๐Ÿฆˆ', '๐Ÿฆ‹', '๐Ÿž', '๐Ÿฆ‚'];
res = myList[Math.floor(Math.random() * myList.length)];
localStorage.setItem('img', res);
}
console.log(res);
document.getElementsByClassName("emoji").innerHTML = res
And several spans with same class:
<span class="emoji" style="font-size: 40px !important;"></span>
The problem is that the "res" doesn't print anything in span.
The console log prints everything fine and LS stores the information perfectly .
I have tried with ID's:
document.getElementsById("emoji").innerHTML = res
And it works perfectly, however only with the first div (as it should i suppose).
What could I be doing wrong in this situation?
Maybe I am not able to see a very simple mistake in my code.

If you specify classname so you have to give index to the class as it puts response only in the first element in the case of id, it is unique but in case of class you have to specify.
document.getElementsByClassName("emoji")[0].innerHTML = res;

Multiple elements can have the same class name. getElementsByClassName returns an array of elements that have the class name (it's Elements not Element). So if you have only 1 element with that class name, you can do document.getElementsByClassName("emoji")[0].innerHTML = res.

getElementByClassName always return array of element, usually can read an element from array as index basis, also similar way can get the element from getElementByClassName.Pls see the below snippet.
const myList = ['๐Ÿ’', '๐Ÿ•', '๐Ÿˆ', '๐Ÿ…', '๐ŸŽ', '๐Ÿฆ“', '๐Ÿ„', '๐Ÿฆ’', '๐Ÿ˜', '๐Ÿฆ”', '๐Ÿฆ‰', '๐ŸŠ', '๐Ÿฆ–', '๐Ÿฌ', '๐Ÿฆˆ', '๐Ÿฆ‹', '๐Ÿž', '๐Ÿฆ‚'];
var res = myList[Math.floor(Math.random() * myList.length)];
document.getElementsByClassName("emoji")[0].innerHTML = res
<span class="emoji" style="font-size: 40px !important;"></span>

Related

Javascript function to just get all elements from getElementsByClassName

First things first, I've looked in a bunch of seemingly related questions that don't directly relate to my problem:
javascript getElementsByClassName from javascript variable
getElementsByClassName doesn't select all my Navigation elements
Javascript: getElementsByClassName not giving all elements
Javascript document.getElementsByClassName not returning all elements
How to change class for all elements retrieved by document.getElementsByClassName
getElementsByClassName vs. jquery
If there is another question that already addresses my specific problem I apologize and please direct me there.
I'm trying to extract opening and current line data from the following page: https://www.sportsbookreview.com/betting-odds/ncaa-basketball/ and it's only returning data for a certain subset of games. The code is below.
convertHalfLines = stringVal => {
let val
let halfLine = false
if (stringVal.substr(-1) === '\u00BD') {
val = parseFloat(stringVal.slice(0,-1))
halfLine = true
} else {
val = parseFloat(stringVal)
}
return halfLine ? val + (Math.sign(val) * 0.5) : val
}
let games = document.getElementsByClassName("_3A-gC")
let gameInfo = Object.keys(games).map(game => {
let teams = games[game].getElementsByClassName("_3O1Gx")
let currentLines = games[game].getElementsByClassName("_3h0tU")
console.log('currentLines',currentLines)
return {
'homeTeam': teams[1].innerText,
'awayTeam': teams[0].innerText,
'homeWagerPct': parseFloat(currentLines[1].innerText),
'awayWagerPct': parseFloat(currentLines[0].innerText),
'homeOpeningLine': convertHalfLines(currentLines[3].getElementsByClassName('_3Nv_7')[0].innerText),
'awayOpeningLine': convertHalfLines(currentLines[2].getElementsByClassName('_3Nv_7')[0].innerText),
'homeCurrentLine': convertHalfLines(currentLines[5].getElementsByClassName('_3Nv_7')[0].innerText),
'awayCurrentLine': convertHalfLines(currentLines[4].getElementsByClassName('_3Nv_7')[0].innerText),
}
})
The code returns data for a certain set of games, which in and of itself is not consistent. Sometimes it returns data for the first six games, sometimes for the first eight, sometimes less or more than these. Is there something I just don't know about JS that I'm missing or is something else going on?

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

tried to change the inner element of dynamic div through class name but its not working [duplicate]

This question already has answers here:
How to use getElementsByClassName in javascript-function? [duplicate]
(3 answers)
Closed 8 years ago.
I have create the dynamic div and now trying to change the inner html of it but its not working please help me here is the code
function like(id)
{
var orgnldiv=document.getElementById(id);
var ndiv=document.createElement('DIV');
ndiv.id = 'like';
ndiv.className="likeclass";
var classname = document.getElementsByClassName("likeclass");
orgnldiv.appendChild(ndiv);
classname.innerHTML="example";
//alert(id);
}
Beware of the s in Elements. That means that you are getting a list rather than a single control.
Check How to use getElementsByClassName in javascript-function?
Use this:
function like(id)
{
var orgnldiv=document.getElementById(id);
var ndiv=document.createElement('DIV');
ndiv.id = 'like';
ndiv.className="likeclass";
orgnldiv.appendChild(ndiv);
var elements = document.getElementsByClassName("likeclass");
for(var i = 0; i < elements.length; i++) {
elements[i].innerHTML="example";
}
}
You get error because getElementsByClassName returns array of elements, not one elements. So you have to work with result like with array. If 1 element return loop will fire only 1 time. If 0 elements it wouldn't fire.
Hope this will help.

Get the highest attribute value from a set of DOM elements [duplicate]

This question already has answers here:
jQuery: How to calculate the maximal attribute value of all matched elements?
(7 answers)
Closed 8 years ago.
I have a set of DOM elements with data attributes. How can I get the maximum value?
<li data-for-something="1"></li>
<li data-for-something="1"></li>
<li data-for-something="2"></li>
<li data-for-something="3"></li>
<li data-for-something="4"></li>
I can use $('[data-some-value]') to get all the li with this attribute, and then loop through them. But I'm not sure what js or jquery methods are available to make this easier.
The best I've got is doing this:
function getMaxAttributeValue(attribute_name) {
var max_value = 0;
$('[' + attribute_name + ']').map(function(){
var this_value = this.attr(attribute_name);
if (this_value > max_value) {
max_value = this_value;
}
});
return max_value;
}
I like this way:
function getMaxAttributeValue(attribute_name) {
return Math.max.apply( Math, $('[' + attribute_name + ']').map(function(){
return Number($(this).attr(attribute_name)) || -Infinity;
}))
}
console.log(getMaxAttributeValue("data-for-something")) // outputs 4
I think #juvian's answer is probably the best, however I fiddled around with this before I saw his answer, so I thought I'm going to share the way I wanted to do it. It's not a function, but works perfectly with your html structure. I made use of the dataset property.
var array = new Array;
$('li').each( function() {
array.push(parseInt($(this)[0].dataset.forSomething));
});
console.log(Math.max.apply(Math, array));
I added this to this fiddle: http://jsfiddle.net/vVkr6/

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