Learn how to extract the value of a DIV element, store it in an array, and utilize it at a later time. JavaScript and jQuery are the

My goal is to gather the data-league values from all of these divs and store them in an array.

https://i.sstatic.net/ratPH.png

What I aim to accomplish: Retrieve all those values, save them, then iterate through them to trigger a .click event on those divs.

I'm unsure if there's a simpler way to achieve this task.

I suppose it also needs to loop through the divs with ID=128 to extract the data-league values, correct?

Quite frankly, I am completely stuck, so any assistance would be greatly appreciated.

Thank you.

Additional information: Essentially, upon clicking a button, all those thumbnails should open in new tabs. Each tab representing a different stream. (Refer to the image)

https://i.sstatic.net/pG4Jy.jpg

Answer №1

The id (128) in the given example has been repeated several times, violating the rule of uniqueness. It is not feasible to iterate through duplicate ids.

To explore other options, you can consider selecting all div elements with a specific class, similar to this code snippet:

var panelDivs = document.getElementsByClassName('videoPanel');

Subsequently, you can loop through this array, retrieve the values of the data-league attribute, and store them for future reference, such as in an array:

var leagueDataValues = [];
for (var j = 0; j < panelDivs.length; j++) {
    leagueDataValues.push(panelDivs[j].getAttribute('data-league'));
}

By storing these values in the array leagueDataValues, you are well-equipped to incorporate them into your script seamlessly.

Answer №2

If you want to select elements that have a specific attribute, such as data-league, you can use the $('[attribute]') selector in jQuery. Once selected, you can loop through these elements using .each();.

Here is an example that demonstrates triggering a click event on every element with a data-league attribute:

$('[data-league]').each(function() {
    $(this).trigger('click');
});

You may also refine the selector to target only those elements that share a specific class name, like videoPanel:

$('.videoPanel[data-league]').each(...);

This will focus on elements that belong to the class videoPanel and possess the attribute data-league.

To extract the value of the data-league attribute into an array, you can do the following:

var leagues = [];
$('.videoPanel[data-league]').each(function() {
    leagues.push($(this).attr('data-league'));
});

Answer №3

If you want to extract all the data-league values and store them in an array, you can use the following code snippet:

var leagues=[];
$('.vedioPnnel').each(function() {
     var league = $(this).data('league');
     leagues.push(league);
});
console.log(leagues);

Answer №4

One approach is to utilize the forEach function in JavaScript as shown below in the code snippet. Another option is:

document.querySelectorAll('[id="127"]');

or

document.querySelectorAll('[data-league]')

function retrieveAllDataLeagues()
{
  var leagues = [];
  Array.prototype.forEach.call(document.getElementsByTagName('div'), function (value, index, traversed) {
    var attrValue = value.getAttribute('data-league');
    if (attrValue) {
      leagues.push({'obj': value, 'data-league': attrValue});
    }
  });
  return leagues;
}


var elementsFound = retrieveAllDataLeagues();


// display the results in the html body
document.body.innerHTML += '<p>To access elements: elementsFound[index]["data-league"]</p>';
document.body.innerHTML += '<p>To trigger the click event: elementsFound[index]["obj"].click()</p>';
document.body.innerHTML += '<p>Elements found:</p>';
for (var i = 0; i < elementsFound.length; i++) {
  document.body.innerHTML += '<div>data-league:' + elementsFound[i]["data-league"] + '</div>';
}
<div class="game-listing-group">
    <div class="bold game-listing-name">CS:GO</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=m0e_tv" data-league="1284">
    <div class="video-thumbnail-con hidden-xs hidden-sm">
        <img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_m0e_tv-320x180.jpg">
    </div>

    <div class="videoPanelTextBg">
        <p class="indexVideoPanelTitle">Dragon lore giveaway NOW</p>
        <span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
    </div>
    <div class="indexVideoPanelGoldCount video-upcoming">
        <i class="glyphicon glyphicon-time"></i>
        <span class="vu-league-start"></span>
    </div>

</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=freakazoid_tv" data-league="1296">
    <div class="video-thumbnail-con hidden-xs hidden-sm videoPanelTextBgActive">
        <img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_freakazoid_tv-320x180.jpg">
    </div>

    <div class="videoPanelTextBg">
        <p class="indexVideoPanelTitle">BIRTHDAY IN 24HOURS! @c9freakazoid</p>
        <span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
    </div>
    <div class="indexVideoPanelGoldCount video-upcoming">
        <i class="glyphicon glyphicon-time"></i>
        <span class="vu-league-start"></span>
    </div>

</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=gripex90" data-league="1301">
    <div class="video-thumbnail-con hidden-xs hidden-sm">
        <img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_gripex90-320x180.jpg">
    </div>

    <div class="videoPanelTextBg">
        <p class="indexVideoPanelTitle">Gripex - Most dedicated Lee sin! Top 50 Challenger</p>
        <span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
    </div>
    <div class="indexVideoPanelGoldCount video-upcoming">
        <i class="glyphicon glyphicon-time"></i>
        <span class="vu-league-start"></span>
    </div>

</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=phantoml0rd" data-league="1346">
    <div class="video-thumbnail-con hidden-xs hidden-sm">
        <img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_phantoml0rd-320x180.jpg">
    </div>

    <div class="videoPanelTextBg">
        <p class="indexVideoPanelTitle">Level 400 Gambler LOL - Cycled over 3,000,000 in s</p>
        <span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
    </div>
    <div class="indexVideoPanelGoldCount video-upcoming">
        <i class="glyphicon glyphicon-time"></i>
        <span class="vu-league-start"></span>
    </div>

</div></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error persists even after implementing the use client at the top of the Next.js component

× You have imported a component that requires the useRouter hook. However, it seems that the component is being used in a Server Component instead of a Client Component. This may be causing an error.https://i.sstatic.net/UD7VtlbE.png "use client &quo ...

Can Vue.js components and traditional Vue instances be utilized concurrently within an application?

Currently, my Laravel application utilizes Vue.js as the frontend JavaScript framework. While I employ components for large scripts, I prefer using a Vue instance in the blade template for smaller scripts. The issue arises with my app.js configuration - f ...

What are the steps involved in manipulating templates following manual $compile?

Currently, I am working on a web application using AngularJS and need to display a list of categories. Each category within the list may contain an array of subcategories. To achieve this, I have developed a recursive directive called category that funct ...

What are the steps to incorporating the League Gothic font into my website design?

Is there a way to incorporate League Gothic font into my website design? Visit the League Gothic GitHub repository Appreciate any guidance on this matter, ...

How come the logout option is not displaying after creating it with Laravel's Bootstrap authentication method?

Check out this navigation bar code snippet: @else <a id="navbarDropdown" class="nav-element" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" a ...

Vue.js - Maintaining input value when model declines updates

I am working on a text input that allows users to enter numbers with a maximum of three digits after the decimal point: <v-text-field type="text" :value="num" @change="changeNum($event)" /> <p>{{ num }}</p> ... export default { data: ...

What's the best way to keep track of the number of objects I've created

Using this HTML code, I can create member objects. However, I also need to determine the count of these member objects for certain calculations. Additionally, when a member object is deleted, the count of member objects should be reduced accordingly. The ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Click on the logo to return to the home page

Logo Link Causing Menu Alignment Issue After setting the logo as a link, the menu unexpectedly shifts to the right. Upon inspecting the menu element, it appears that there is an additional hidden menu link on the left side leading to index.html. Can anyon ...

Share the digital masterpiece generated using JavaScript

Is there a way to upload an image that is nested within the img element of a page, for example when the image was dynamically created using the canvas2image jQuery plugin? I have come across the uploadify plug-in, but I'm unsure how to implement it in ...

An issue with the canvas: The distortion of array values in Javascript causing problems when drawing on the canvas

click here for image description click here for another image descriptionI've been playing around with some JavaScript animations involving random-sized dots floating on a canvas and connecting when the distance between them is less than 150px. The co ...

The <a> tag with href attribute is mistakenly identified as an external link when used in conjunction with the <base> tag

I am currently working with jQuery UI tabs using jquery 1.11.1 and jQuery ui 1.11.1. Within the <base> tag in the head>, I have the following: <base href="http://mytestdomain.com/" /> Upon loading the page, jQuery UI creates two tabs from ...

Increasing numerical section of text with JavaScript

Is there a way to increment the numeric part at the end of a string in JavaScript when certain actions occur? For example: var myString = 'AA11111' increaseStringValue(myString) # Updated value of myString => 'AA11112' Additional ...

Encountering an issue with the for loop in React Native when using FlatList

As a beginner in programming, I am eager to dynamically render a list. The Navbar parent component holds the state with different Food Types categories such as Mexican and Chinese, each with its corresponding menu. My goal is to display each Food Type fol ...

Transferring the control's identifier to JavaScript using ScriptControlDescriptor

In my CreateChildControls() method, I am creating a control: HtmlGenericControl mycontrol= HtmlGenericControl("li"); mycontrol.ID = "controlID"; controlId = mycontrol.ID; protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors() { ...

"You have an undefined error with 'Navigator.' Check out the JSHint before using the forecast API that utilizes JSON

I'm tasked with creating a small app prototype for a school assignment that interacts with the Forecast.io API. While I don't have much experience working with APIs, the code seems clean and functional. However, within Brackets, JSHint is flaggi ...

What is the best way to transfer a JavaScript object with string values containing quotes from node.js to the browser?

I have a node/express application and need to send a JavaScript object to the browser. Currently, I achieve this by using JSON.stringify on the object and then embedding it into the HTML: In my Node.js/Express code: var myObject = /* fetched from databas ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

Knockout JS: Choosing specific dropdown elements

My array doorsForSite contains a list of doors, each with its own set of schedules. Here is how it looks: var scheduleList = new[] { new { ScheduleId = "Schedule1",ScheduleName = "Always On" }, new ...

Divide the adaptive navigation bar into two separate columns

I'm currently working on a website called and utilizing the free version of . The menu will be displayed for devices 400px and smaller. Is there a way to divide its columns into 2 like this? https://i.sstatic.net/Ac5Do.jpg I am unsure how to adjus ...