Exploring query options in jQuery for searching text using the :contains selector

Why is the if statement below not giving me the expected results? Every time it just turns the paragraph yellow, even when the word doesn't match the :contains expression. Here's the query I'm using.

$(document).ready(function() {
  if ($("p:contains(x)")) {
    $("p").css("background-color", "yellow");
  } else {
    $("p").css("background-color", "red");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <script src="scripts/jquery-3.2.0.min.js"></script>
  <script src="scripts/script.js"></script>
  <link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
  <h1>This is a heading</h1>
  <p class="hand">This is a paragraph</p>
  <p>glow</p>
  <p>The heading, paragraph and button element have a click event defined. Click on each element to display which element triggered the event.</p>
  <div style="color:blue;"></div>
</body>

</html>

Answer №1

I couldn't find a mention of the variable x, so I decided to create it on my own :). The code below checks if the string "glow" is present in a paragraph and changes the background color to yellow. If a paragraph does not contain "glow", the background color changes to red. It would be better to toggle classes rather than directly modifying the CSS.

$(document).ready(function(){
  $("p:contains('glow')").css("background-color", "yellow"); 
  $("p").not(":contains('glow')").css("background-color", "red");
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</head>
<body>
<h1>This is a heading</h1>
<p class="hand">This is a paragraph</p>
<p>glow</p>
<p>The heading, paragraph and button element have a click event defined. Click on each element to display which element triggered the event.</p>
<div style="color:blue;"></div>
</body>
</html>

Answer №2

When using a conditional statement, you need to verify if the value of length is greater than 0. If not, you can simply do:

$("p").css("background-color", "red");
$("p:contains(glow)").css("background-color", "yellow"); 

This code snippet sets the background color of all paragraphs to red, and the one containing "glow" to yellow.

$(document).ready(function() {
  if ($("p:contains(glow)").length > 0) {
    $("p").css("background-color", "red");
    $("p:contains(glow)").css("background-color", "yellow");
  } else {
    $("p").css("background-color", "red");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
  <h1>This is a heading</h1>
  <p class="hand">This is a paragraph</p>
  <p>glow</p>
  <p>The heading, paragraph and button element have a click event defined. Click on each element to display which element triggered the event.</p>
  <div style="color:blue;"></div>
</body>

</html>

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

Leveraging node modules in the browser using browserify - Error: fileType is not recognized

I am currently attempting to utilize the file-type npm package directly in my browser. Despite my efforts, I have encountered an error when trying to run the example code: Uncaught ReferenceError: fileType is not defined (Example code can be found here: ...

Swap the text with a dropdown selection area

I have developed a custom script that is meant to replace text within an HTML page using content from an external .txt file, all done with the assistance of jQuery. However, for some reason, it is not functioning as expected: <!DOCTYPE html> <h ...

Tips for deleting "Category: [category name]" in Wordpress

I have attempted various solutions found in previous threads, but none of them seem to work for me. Here is a screenshot I am looking to remove the text from the header in the category and only display [category name]. Can anyone assist me with this, ple ...

Display issues occur with Bootstrap 4.2.1 flex-box layout columns exceeding the browser edge

Why does COLUMN02 extend beyond the browser's edge when using flex-basis for column widths? What mistake am I making? Unfortunately, it doesn't display correctly in the code snippets here but works in the fiddle. TIA! http://jsfiddle.net/dragont ...

The output is displaying an Object instead of a numerical value in JSON

When I try running the URL in Chrome, the output I receive is: { "Train_score": { "0": 0.9892473118 }, "Test_score": { "0": 0.9831932773 } } However, when I attempt to use the following code to retrieve the JSON data using Javascript, co ...

The simplest way to increase the size of a child element in order to generate a scrollable area

When working with HTML, it's important to consider how the size of a child div affects the parent div. If the child div is larger than its parent, scrollbars will appear on the parent div if the appropriate style rules are set. However, I'm inte ...

Issues with inputmask functionality in Vue.js when using jQuery are causing it to

I'm currently facing an issue while attempting to implement the inputmask plugin as a Vue.js directive. The error message I'm encountering reads: $(...).inputmask is not a function Once I resolve this error, I will need the input value to be sy ...

Angular 4 - Automatically scroll to specific list item based on search query input

While I can achieve this with custom JavaScript, I'm curious if Angular 4 has any built-in features that could help. I have a list of checkboxes that are scrollable and a search input above them. My goal is to enable users to quickly jump to a section ...

How can I successfully transmit the entire event during the (change) event binding with ng-select in Angular 14?

I'm working on Front end Code <ng-select formControlName="constituencyId" placeholder="Select Constituency" (change)='onContituencyChanged($event)'> > &l ...

How can I move a TableItem from one material UI component to another using drag-and-drop?

I am facing an issue where I need to drag a ListItem from one List component to another. I am uncertain about how to accomplish this in Material UI. ...

What's the best way to implement a conditional header in React?

I am looking to create a conditional display of the Header based on different pages. Specifically, I want the Header to be hidden on the Home page and shown on other pages like posts page, projects page, etc. I have been brainstorming possible solutions f ...

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

Fetching data from Page 1 and passing it to Page 2 using Javascript

I'm currently experiencing an issue with my AJAX function where it needs to transfer a value from page 1 to page 2 for storage. Let's start with the AJAX function on page one: top.location.href = 'http://www.something.com/redirect.php?emai ...

Utilize jQuery to enclose nested elements within a parent element

There is a Markup presented below, where this HTML content is being generated from Joomla CMS. I am seeking a jQuery method to reorganize this HTML structure without modifying its PHP code. <div class="item column-1"> <div class="page-header"& ...

Updating the state value of a variable that utilizes a custom Hook: a step-by-step guide

After watching a video by Dan Abramov, I decided to optimize my component by creating a custom Hook called useFormInput. This hook handles the state and onChange functionality for all of my form input fields. Everything was working perfectly until I neede ...

Ways to Manage modals responses as services in AngularJS

I am a beginner in the world of JavaScript and AngularJS. I am fascinated by some of the concepts within JS, like trying to create a modal service using the example I found online. I am eager to delve deeper into what exactly is happening under the hood, e ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

Getting the id of a single object in a MatTable

I'm currently working on an angular 8 application where I've implemented angular material with MatTableDatasource. My goal is to retrieve the id from the selected object in my list: 0: {id: "e38e3a37-eda5-4010-d656-08d81c0f3353", family ...

What is the process for connecting an event to the <body> element in backbone.js?

Could it be done? For example, like this: ... interactions { 'click button' : 'performAction' } ... ...

What is the best approach to defining a type for a subclass (such as React.Component) in typescript?

Can someone help me with writing a type definition for react-highlight (class Highlightable)? I want to extend Highlightable and add custom functionality. The original Highlightable JS-class is a subclass of React.Component, so all the methods of React.Com ...