What is the best way to utilize window.find for adjusting CSS styles?

Incorporating both AJAX and PHP technologies, I have placed specific text data within a span element located at the bottom of my webpage. Now, my objective is to search this text for a given string. The page consists of multiple checkboxes, with each checkbox corresponding to a particular value that needs to be searched.

Objective: Employing a loop mechanism, iterate through all the checkboxes present on the page. Search the entire page for each checkbox's value (ideally within the text contained in the span informed by AJAX). If a match is found, modify the CSS style color of that particular checkbox.

The current state of my code involves a form containing checkboxes where they are named "comment" and possess unique IDs:

<input type="checkbox" name="comment" id="hjl1" value="the comment." 
 onclick="createOrder()"><label for="hjl1" onclick="createOrder()" 
 title="comment"> textual representation for this checkbox </label>

Upon activation, using JavaScript, I traverse through every checkbox within the form.

var comment=document.forms[0].comment;
var str="";
var ii;
for (ii=0;ii<comment.length;ii++)
  {str=comment[ii].value;}

My next step involves integrating window.find into that loop to verify if that particular value exists on the page.

if (window.find) {
            var found = window.find (str);
            if (!found) { 
         document.getElementById("?????").style["color"] = "red";
           }
        }

The concept revolves around checking for the presence of "the comment." value on the page when its corresponding checkbox is activated. Upon discovery, the checkbox label will display the CSS style color as red.

I aim to consolidate these concepts, yet numerous obstacles hinder progress. How can I access elements by their IDs within this loop? Is it feasible for window.find to scan the text generated by PHP in my span?

Would it prove more efficient to abstain from utilizing window.find entirely?

var source = document.getElementsByTagName('html')[0].innerHTML;
var found = source.search("searchString");

This process bewilders me as I am relatively inexperienced. Your patience and time spent reading thus far are sincerely appreciated.

Answer №1

Initially, I made a mistake and wrote code to highlight text within the page.

Sure, using window.find is suitable for this purpose since you only need to determine if the value exists or not. However, its behavior may be a bit strange (scrolling to the bottom) when used in frames.

I also included a function for your onClick, although I'm uncertain if this is desired. When clicked, it will change the color of the label if the text is found.

Here's a brief example:

function checkThis(ele) {
  var str = ele.value;
  if (window.find) {
    var found = window.find(str);
    if (found) {
      var id = ele.getAttribute('id');
      var lbl = document.querySelectorAll('label[for="' + id + '"]');
      if (lbl) lbl[0].style.color = "red";
    }
  }
}

window.onload = function() {
  var comment = document.form1.getElementsByTagName('input');
  for (var x = 0; x < comment.length; x++) {
    if (comment[x].type == 'checkbox') {
      var str = comment[x].value;
      if (window.find) {
        var found = window.find(str);
        if (found) {
          var id = comment[x].getAttribute('id');
          var lbl = document.querySelectorAll('label[for="' + id + '"]');
          if (lbl) lbl[0].style.color = "red";
        }
      }
    }
  }
}

first comment.
other comment.
some comment.
the comment.
whatever comment.
not this comment.

Answer №2

Here is a sample function code to try out:

function loopy() {  
   var comment=document.forms[0].comment;
   var txt="";
   var ii;
   for (ii=0;ii<comment.length;ii++) {
    if (comment[ii].checked) {
        str=comment[ii].value;
        id = comment[ii].id;

        nextLabelId = comment[ii].nextSibling.id;


        if (window.find) {        
            var found = window.find (str);
            if (found == true) {
                document.getElementById(nextLabelId).className = 'selected';                
           } 
        } else {
            alert('not supported');
        }
    }
  }
}

If you want to retrieve the checkbox id, simply include id = comment[ii].id in your loop.

To change the color, utilize class names and CSS styling. For example, to change the label after the checkbox to red, find the label's id using nextSiblings and apply the .selected class name. Remember to remove the coloring if the box is unchecked.

The use of find() may not be supported by all browsers and may have limitations when searching content injected via AJAX. Testing is recommended in such cases.

Migrating this code to jQuery might offer easier functionality for some features.

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

A fresh PHP page escapes from the confines of an iframe and expands to occupy the entire

When calling a new url from inside an iframe, the goal is for the new url to break free from the confines of the iframe and appear full screen. The challenge lies in not having control over the call to the new php file, as it is initiated by a credit card ...

The postMessage function in my Javascript SlackBot seems to be flooding the channel with messages

I am currently setting up a Slack bot using JavaScript combined with several useful libraries. The main function of this bot is to execute a postMessageToChannel method whenever a user in the channel mentions the specific keyword "help." However, I am fa ...

I encounter a CORS issue on Heroku, but strangely it only occurs after 20 minutes of deploying. Prior to that time frame, everything functions seamlessly

Today, I encountered a strange issue while hosting my first Node JS backend on Heroku. Everything runs smoothly when I register/login immediately after deploying the backend. However, if I try to register/login after about 15 minutes, I start receiving a C ...

Absolute positioning causes an element's height to increase

As I delve into the realm of typographical animations and seek to calculate the baseline of a font at various sizes, I've stumbled upon a peculiar discovery: It appears that the height values of elements tend to increase in an erratic manner when thei ...

Adding the p5.js library to Stackblitz IDE: A step-by-step guide

Recently, I've been using Stackblitz as my IDE to improve my coding skills on my Chromebook. While it has been effective in many ways, I have encountered difficulties when trying to integrate the p5 library. As a beginner in programming, I only grasp ...

JavaScript: Responding to the fetch response based on certain conditions

I am currently working with a fetch() request that can either return a zip file (blob) or a JSON object in case of an error. The existing code successfully handles the zip file by sending it to the user's Downloads folder. However, when a JSON respons ...

Ways to retrieve the current state within a function after invoking the setState method

I'm currently working on a function to store the blogPost object in a document within my Firestore database. The process I have in mind is as follows: Click on the SAVE button and initiate the savePost() function The savePost() function should then ...

What is the process of transforming a string into an angular binding?

I have a variable called message that contains the text "you are moving to {{output.number}}". I attempted to insert this into a div element using $("#message").html(message); However, it just displayed the entire string without replacing {{output.number ...

The HTML page is displaying the Express.js GET request

As a beginner in express.js, I'm encountering an issue where data sent to the client is displayed directly in the browser instead of appearing as a preview. Can someone please review my code and help me identify what I'm doing wrong? app.use(cors ...

Using an image tag with dual quotes in Vue.js

I am currently working on a feature where users can upload an image and then have it displayed after the upload is complete. However, I am facing an issue where the response link of the image contains a double quote, and when I use the <img> tag to ...

Steps for building an API to connect to our proprietary database using the WSO2 API manager

Currently, I am looking to share my data from my personal postgresql database by creating an API. In this case, I plan on utilizing the WSO2 API manager for the process. I am uncertain if I am proceeding in the correct manner, so any advice on the differe ...

The focus and blur events for the document in a content editable iframe are not activated by Chrome

As I modify the content of an iframe while it is in focus, I have noticed that this seems to function properly in Firefox. However, I am facing issues as the focus and blur events do not seem to trigger in Google Chrome! var iframe = $('#iframe') ...

The process of parsing dates with MomentJS functions correctly for two dates, however, it displays 'Invalid Date' for the third date

I've tried over 50 solutions from Stack Overflow posts, but nothing seems to be working for me. I have three dates: Date 1: 2018-10-28T17:21:38Z Date 2: 2020-10-28T22:29:30Z Date 3: 2021-10-28T17:21:38Z Attempting to parse them into readable formats. ...

Utilizing Javascript to interact with GroupMe API through POST method

I've been working on creating a client for GroupMe using their provided API, but I'm stuck and can't seem to figure out what's going wrong. curl -X POST -H "Content-Type: application/json" -d '{"message": { "text": "Nitin is holdi ...

Steps to update the toolbar color of Mui DataGrid

Check out this unique custom Toolbar I created specifically for Mui dataGrid function CustomToolbar() { return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensit ...

Error in finding the element with Selenium webdriver 2.0 was encountered

I can't seem to find the element with the specified class name. Here's a snippet of the HTML code: <a class="j-js-stream-options j-homenav-options jive-icon-med jive-icon-gear" title="Stream options" href="#"></a> I attempted to gen ...

How can I prevent ng-blur from triggering when ng-readonly is set to true in AngularJS?

I am currently working with AngularJS and have run into an issue when combining ng-blur with ng-readonly. Even though ng-readonly is set to true, ng-blur still triggers (if the input field is clicked and then somewhere else is clicked). In this example, n ...

Rotating the camera in first person perspective using Three.js

After struggling to find updated help on first player rotation in three.js, I am facing a challenge where most of the solutions provided are using functions that no longer exist in the current library version. I am attempting to implement a feature where ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

Using jQuery to create a dynamically moving div that forms an endless wall

In order to create a continuous wall that pulls text from a database and displays it, I've developed the following code: $(function() { var x = 0; var y = 100.0; var z=0; setInterval(function() { x -= 0.1; y -= 0.1; ...