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

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/

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?

I need to remove a specific object from inside of an array in JavaScript [duplicate]

This question already has answers here:
Remove array element based on object property
(12 answers)
Closed 8 years ago.
This is my first time asking a question so go easy on me.
I am currently in class learning JavaScript and am loving it so far. I am having issues with one of our assignments however.
I have an array with 4 objects inside of it. My current goal is to remove a specific object from the array. It's not on the end so I would assume I need to use a for loop to do so, but am having trouble with the syntax.
My current code is as follows:
var devMountainEmployees = [];
var tyler = {
name: 'Tyler',
position: 'Lead Instructor/Engineer',
spiritAnimal: 'Honey Badger'
};
var cahlan = {
name: 'Cahlan',
position: 'CEO',
spiritAnimal: 'butterfly'
};
var ryan = {
name: 'Ryan',
position: 'Marketing',
spiritAnimal: 'fox'
};
var colt = {
name: 'Colt',
position: 'Everything really',
spiritAnimal: 'Young Male Horse'
}
devMountainEmployees.push(tyler, cahlan, ryan, colt);
console.log(devMountainEmployees.length);
The one I want to remove is cahlan and I need to use a loop.
Thanks for your help guys.
You don't need a loop to remove a known object from an array, you can find the offset with indexOf and use splice to remove it.
devMountainEmployees.splice(devMountainEmployees.indexOf(cahlan), 1);
UPDATE:
Since you need to use a loop, do this:
for(var i = 0; i < devMountainEmployees.length; i++)
{
if(devMountainEmployees[i] === cahlan)
{
devMountainEmployees.splice(i, 1);
break;
}
}
If you know the index of the object you would like to remove, then you can use splice
devMountainEmployees.splice(1, 1) (first is the index, second is the number to remove)

javascript getElementsByClassName not working with <select> [duplicate]

This question already has answers here:
How to use getElementsByClassName in javascript-function? [duplicate]
(3 answers)
Closed 8 years ago.
I am trying to use getElementsByClassName to make my select's options jump to their URL's depending on the value:
http://www.example.com/?page_id="value"
Here's what I've done: http://jsfiddle.net/VvLXk/2/
But it's not working.
I know I can use the getElementByID but I have three select elements (and I might add more). I believe it only applies to one element. And for that reason I have resorted to getElementsByClassName which is not working.
What is wrong with my code? Javascript / JQuery solutions are welcome.
As discussed in How to use getElementsByClassName in javascript-function?, getElementsByClassName() provides a collection of elements. To assign an event handler, you'll have to iterate over it and modify each individual element.
for (var i = 0, l = dropdown.length; i < l; i++) {
dropdown[i].onchange = onCatChange;
}
Along with that, you can then reference the single dropdown that the event was triggered for with this inside the handler function.
function onCatChange() {
if ( this.options[this.selectedIndex].value > 0 ) {
// etc.
}
}
Modified fiddle: http://jsfiddle.net/jLLHH/ (note: logs rather than redirecting)
This question has been answered here : How to use getElementsByClassName in javascript-function?
http://jsfiddle.net/VvLXk/9/ here is a sample of it working :
var dropdown = document.getElementsByClassName("page-dropdown")[0];
function onCatChange()
{
if ( dropdown.options[dropdown.selectedIndex].value > 0 )
{
location.href = "http://www.example.com/?page_id="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
What you are selecting will return array, please try this:
var dropdown = document.getElementsByClassName("page-dropdown");
function onCatChange()
{
alert(dropdown[0]);
if ( dropdown[0].options[dropdown[0].selectedIndex].value > 0 )
{
window.location.href = "http://www.example.com/?page_id="+dropdown[0].options[dropdown[0].selectedIndex].value;
}
}
dropdown[0].onchange = onCatChange;
Hope this helps.. Cheers !!

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.

select an array of elements and use them

Using this syntax:
var position = array($('#ipadmenu > section').attr('data-order'));
I cannot get my code to work. I have never used arrays before so im kind of lost on how to use them. (especially in jquery).
How would I make an array of all section elements and associate the value of data-order to that list. Example:
first section - data-order:1
second section - data-order:2
etc and then use that info afterwards.
Thank you!
Since .attr just gets one attribute -- the first one found by the jQuery selector -- you need to build your array element by element. One way to do that is .each (you can also use .data to extract data attributes):
var position = new Array;
$('#ipadmenu > section').each(function() {
position.push($(this).data('order'));
});
alert(position[0]); // alerts "1"
This will be an indexed array, not an associative array. To build one of those (which in JavaScript is technically an object, not any kind of array) just change the inner part of your .each loop:
var position = {};
$('#ipadmenu > section').each(function(i) {
position["section"+i] = $(this).data('order');
});
The resulting object position can now be accessed like:
alert(position['section1']); // alerts "1"
A different approach involves using jQuery.map, but since that only works on arrays, not jQuery objects, you need to use jQuery.makeArray to convert your selection into a true array first:
var position = $.map($.makeArray($('#ipadmenu > section')), function() {
return $(this).data('order');
} ); // position is now an indexed array
This approach is technically shorter than using .each, but I find it less clear.
Javascript:
var orders = [];
$('#ipadmenu > section').each(function() {
orders.push($(this).data('order'))
});
HTML:
<div id="ipadmenu">
<section data-order="1">1</section>
<section data-order="2">2</section>
</div>
You will want to do something like this:
// Get the elements and put them in an array
var position = $('#ipadmenu section').toArray();
console.log(position);
// Loop through the array
for (var i = 0; i < position.length; i++){
// Display the attribute value for each one
console.log("Section " + i + ": " + $(position[i]).attr('data-order'));
}
Working example here: http://jsfiddle.net/U6n8E/3/

Categories

Resources