Update each initial .not('class') using Jquery

My attempt at creating a live search with an effect in jQuery is proving to be challenging as I am struggling to capture the first word in the text. I have attempted to wrap each word in a span like this:

<span class="word word-this" id="word-#" aria-hidden="true">this</span>

In my script, I am trying to add a "readed" class to the word behind the one I am searching for. However, every time I move on to the next instance of "this", all previous instances are tagged with the "readed" class. It looks something like this:

var word = function(word) {
  $('span').each(function() {
    if ($(this).not('.readed') && $(this).hasClass('word-'+word)){
      // transformation
      $('.word-'+word).first().css('color', 'red').addClass('readed');
    }
  });
};

The issue I am facing is that it detects the first occurrence of the word, but it fails to identify subsequent occurrences - it remains stuck on the initial one. It seems to overlook the fact that the "readed" class has been added. I am unsure if this problem stems from the use of .first(), .not(), or some other factor.

Answer №1

I came across two issues.

  • $('.word-'+word).first() represents the initial span with .word-<word>.
  • $(this).not('.readed') is considered as an object, therefore it always evaluates to true in an if statement condition.

Below is the corrected code:

var word = function(word) {
  $('span').not('.readed').each(function() {
    if ($(this).hasClass('word-'+word)) {
      // make changes
      $(this).css('color', 'red').addClass('readed');
      // break out of the loop
      return false;
    }
  });
};

I discovered a more concise approach.

var word = function(word) {
  $('span.word-'+word).not('.readed').first().each(function() {
    $(this).css('color', 'red').addClass('readed');
  });
};

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

I can't seem to get the Font Awesome icons to display properly. What could be the issue?

How can I get Fontawesome icons to display properly in the footer? Despite having my CSS and HTML files in the same directory, the icons remain invisible. Additionally, the page seems to be loading slower than usual. I have provided all necessary informati ...

What is the best way to enable my array to function properly when assigning non-consecutive numeric indexes using jQuery?

I have a dynamic XML file generated from a database that contains both an ID and a name for each item. It is structured as follows: <item> <id>1</id> <name>FirstName</name> </item> ... and so forth ... I am atte ...

What methods can I use to ensure a jQuery dialog stays visible at all times?

To avoid centering the dialog on the screen, I am specifying the top and left coordinates of the box. The positioning is set up so that it aligns next to a link without being open until clicked. $("#error").dialog({ bgiframe: true, autoOpen: false ...

Sorting Datatables using ajax method

I am using a basic datatables setup with will_paginate. <table id="users" class="display" data-source="<%= url_for(:controller => "/account", :action => :paginate, :format => :json) %>"> <thead> <tr> <th> ...

What is the best method to send user information from a registration form to a MySQL database table using AJAX without having to refresh

Currently facing an issue where user registration data (email, username, password) is not being submitted to the register table tbl_register when the submit button is clicked. Utilizing PHP with AJAX to prevent page refresh upon clicking submit and sendin ...

Issue with Twitter Bootstrap 3 Sticky Footer functionality in IE11 and IE Edge

My website works perfectly on Chrome, but I'm having issues on Internet Explorer. I would really appreciate your help. The website I am working on is: I am trying to implement a sticky footer on IE, but for some reason, it's not working as expe ...

Access exclusive RSS feeds from Twitter

I am facing a challenge in showcasing the most recent 3 tweets from Twitter on my client's website. The tweets are marked as private, making it difficult to access them. How can I pass the username and password to retrieve these latest tweets? Is it p ...

Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery? My element has a relative position, so the offset() function only gives me the offset within the parent. Unfortunately, I have hierarchical divs, ...

Tips for extracting data from JQgrid rows

I've been working with Jqgrid, attempting to retrieve row values on the Context menu click event. Unfortunately, I haven't been successful in getting the values. Below is the code I've been using to try and obtain the row values: loadComple ...

Incorporating chart.js into a current Django page: a step-by-step guide

I am currently developing a website that includes a feature displaying total hours worked by an employee. I am looking to enhance this function by also showing the hours worked for each day in a month. I have successfully created a chart for this purpose, ...

Click on every link to reveal a hidden div

When I click on and select the first link in the mainPart, I want to automatically select the first subLink div in the secondPart while hiding the other subLink classes. This sequence should be maintained: when the second link is selected, the second sub ...

Is it possible to create a masonry-style layout with two columns that is responsive without

Is there a way to organize multiple divs of varying heights into two columns that display immediately one after the other, without relying on JavaScript or libraries like packery or masonry? I've experimented with using display: inline-block in this ...

When making a request through local apache, the POST method is switched to GET

I've been attempting to send a post request using the code below. However, the request is being sent as a GET instead of POST. How can I resolve this issue? $.ajax({ url: 'https://www.exampleurl.com', method: 'POST', h ...

expanding the div based on the filtered content inside

My current setup involves using jQuery filters to refine the selection of products. All the products are contained within their own individual divs, which are then placed inside a single "large div". When a filter is applied, the divs containing products ...

Find the highest-level parent element using JQUERY and select all of its child divs excluding the current

<div class="topDiv"> <div class="repeaterDiv"><input type="radio" id="rpt_01_rb" /> <input type="checkbox" id="rpt_01_cb1" /> <input type="checkbox" id="rpt_01_cb2" /> <input ty ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

Having issues with the Bootstrap tabs code provided in the documentation not functioning correctly

Exploring the world of Bootstrap 5 tabs led me to copy and paste code from the official documentation (https://getbootstrap.com/docs/4.1/components/navs/#javascript-behavior), but unfortunately, it's not functioning as expected: clicking on a tab does ...

`Slide bootstrap carousel without moving other elements`

.carousel { position: relative; height: 500px; .carousel-inner .item { height: 500px; } .carousel-indicators > li { margin: 0 2px; background-color: $maincolor; border-color: $maincolor; opacity: .7; ...

What is the best way to utilize jQuery for submitting a form through ajax and then extracting and interpreting the response?

My code has been simplified to include only the necessary elements for this example. I am able to submit the form successfully, but I am looking to understand how to handle error responses so that I can parse and display them. This is what I have attempte ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...