Generating an Array using Jquery

I am working with two functions. The first function takes the input from users in a text box, appends it to a div, and then displays it on the HTML page. The second function is supposed to change the styling of the word entered by the user, alternating the color and background for each word. However, I am facing some issues with the second function. Since I have never created an array using jQuery before, I suspect there might be a syntax error causing my code to run as if the second function doesn't exist. Any advice or suggestions would be greatly appreciated.

Thank you

Below are the two functions:

function listWordsUsed(wordUsed) {
    var userTrials = $('#userGuesses');
    var divisor = $("<div>" + wordUsed + "</div>");
    divisor.hide().appendTo(userTrials).fadeIn(7000);
    return;
} //End of function listWordsUsed(wordUsed) 

function addStyleToAnswers(wordUsed) {
    listWordsUsed(wordUsed);
    theGuess = $("div").toArray();
        for (i=0; i< theGuess.length; i++)
        {
            if (i % 2 == 0)
            {
                $("#userGuesses").addClass("oddGuess");
            } //if (i % 2 = 0)
            else
            {
                $("#userGuesses").addClass("evenGuess");
            } //else
        } //for (i=0; i< wordUsed.length; i++)
} //function addStyleToAnswers(wordUsed)

Here is the CSS related to these functions:

.oddGuesses {
    color: orange;
    background-color: blue;
}

.evenGuesses {
    color: blue;
    background-color:orange;
}

Answer №1

To iterate through a jQuery object, you can utilize the .each() method. Check out http://api.jquery.com/each/ for more information.

function displayAnswer (textDisplayed) {
  var userOptions = $('#userChoices');
  var container = $('<div class="option">' + textDisplayed + '</div>');
  container.hide().appendTo(userOptions).fadeIn(7000);
  return;
}

function applyStyleToOptions(textDisplayed) {
  $('.option').each(function(index){
    if (index%2 === 0) {
      $(this).addClass('light')
    } else {
      $(this).addClass('dark')
    }
  });
}

displayAnswer();
applyStyleToOptions();

If you only need to style alternate elements, consider using CSS with div:nth-child(odd) and div:nth-child(even), unless compatibility with IE8 is not essential.

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

Using Bootstrap in Rails: Positioning a dropup to align with another element in a footer

I am attempting to align the content as a footer, but having trouble with the dropup not lining up properly: <footer class="footer"> <div class="container-fluid"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> &l ...

How can you effectively enhance images for optimal web performance? (Transitioning from Figma wireframe to code)

As I work on building my portfolio from scratch, one challenge I am facing is how to include high-quality images without sacrificing site speed or image resolution. I used Figma to create wireframes, but when I exported the images, I noticed a significant ...

What are the methods for adjusting the height of one div in relation to another div?

How can I make the height of the first div equal to the dynamic height of the second div, when the second div contains a lot of dynamic data with an unpredictable height? <div style="width: 100%;"> <div class=& ...

Transform your image using the Bootstrap framework

I am attempting to create a similar banner using bootstrap. You can view the demo of the banner here. https://i.stack.imgur.com/JXLNY.png I'm struggling to understand how to achieve this in bootstrap 3 and where to begin. Should I use rows and colum ...

How to retrieve the current key from an array in PHP?

$arr = ( array('1231415'=>array('foo'=>'bar', 'test'=> 1)), array('32434'=>array('foo'>'bar', 'test'=> '0')), array('123244'= ...

Converting a data-attribute list into an array

My current setup includes an image with the following properties: <img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg"> I am wondering how I can extract the list of images from the data ...

Content is not centered and remains at a consistent size

My struggle is with changing the font size and alignment on my website. Despite numerous attempts, I can't seem to get it right. The text is currently left-aligned when I want it centered, and I also need it to be larger in size. Take a look at my cod ...

What is the determined method for calculating the pixel size of an SVG image?

Did you know that the Stackoverflow logo is actually an <a> element with a SVG image as its background? #hlogo a { text-indent: -999em; display: block; width: 200px; height: 50px; background-image: url("img/sprites.png?v=c4222387 ...

Using dots instead of lines for the carousel indicators in PrimeNG

I'm currently working on a carousel feature, but I want to change the indicators from lines to small dots. I know the solution lies within the CSS files, but I'm not sure how to implement it. I think I need to create a new CSS class, but I could ...

When I include a class in a checkbox label, the CSS ceases to function properly

Apologies for my lack of understanding, but I am facing an issue with applying an attribute to a label element with class "c". It seems to work fine with other objects, like buttons, but not with labels. I cannot figure out why such a simple thing is not w ...

What might be causing the invisibility of a particular div element?

Here is the layout in the div element: <div class=" wrap clear"> <div class="block pink float"></div> <div class="block blue float"></div> <div class="block orange float"& ...

Include an arrow in a personalized horizontal scroll bar using Angular and HTML

After styling a horizontal scrollbar for my chartjs graph, I attempted to add arrows using material icons like <mat-icon>keyboard_arrow_left</mat-icon>. However, I am struggling to align them next to the left and right of the scrollbar. Can any ...

Encountering a 400 Bad Request error while using the SharePoint 2013 Rest API

I am currently developing a web component that utilizes jQuery for making a REST API request to rename a SharePoint subsite. The functionality is working as expected when using a custom button on EditForm.aspx within a list, and it also functions correctly ...

Achiever.js - Incorporating incremental progress with half stars instead of whole stars

Hello there! I've been utilizing Rater.js in my current project, and so far it has provided me with satisfactory results. However, I have encountered a particular issue that I am struggling to resolve on my own. It would be greatly appreciated if you ...

Excessive content - letter "y" disrupts the row layout on mobile devices

I have created a custom CSS class called "custom-class" and applied it to the col div. This column contains dynamic images, so I have added a vertical scrollbar property to handle the overflow. While everything looks fine on a desktop, the layout breaks o ...

Grails Update Alert: Deletion of 'xitem' item not permitted

Developing with Grails and JQuery def update(Bookmark bookmark) { if (params.item) { def portfolio = Portfolio.read(params.item) bookmark.addToItems(portfolio.id) bookmark.addToPortfolios(portfolio.id) } else if (params.xitem) { bookmark. ...

Generating arrays in the output of a Talend JSON field is essential for organizing and structuring

Having trouble with the tWriteJSONField component in Talend, specifically with pushing data into a tRESTClient object that has very specific API requirements. I can extract the required data using tWriteJSONField but it's not in the correct format tha ...

Having trouble implementing button functionality in a web app using JS, jQuery, HTML, and CSS along with an API integration

I am currently developing a web search engine that utilizes the Giphy API... However, I've encountered difficulties with the button function. I have created buttons to modify the page format and adjust the number of search results displayed.... The We ...

Listing the dates of the month and comparing them with dates from another month using jQuery

Is there a way to generate a list of dates in a month that includes the dates from other months, similar to how the jquery datepicker with showOtherMonths: true works? I was considering creating a calendar with 7 columns (Sun-Sat) and 6 rows to accommodat ...

`The Art of Binding() with Objects Created on the Fly`

Currently facing challenges with rebinding something using a dynamically created object from prepend. Despite trying several methods, I am only able to unbind. Seeking assistance. $(document).ready(function(){ $(".newdir").click(function(){ $(".d-exp ...