Using the CSS selector :contains() does not function properly when there are line breaks present

<div>A very lengthy 
text that goes on and on</div>

When rendered,

A very lengthy text that goes on and on
will appear as HTML removes the line breaks.

However, locating the div using the :contains() CSS selector is challenging due to the line break:

// Returns an empty array
$(':contains("A very lengthy text that goes on and on")');

Is there a method to select the div content while disregarding the line break?

Note: Without adding the line break in the selector, I aim to choose the div without prior knowledge of the presence of a line break (as it's based on what the user sees, who might not be aware of the line break).

Answer №1

If you're looking to customize the behavior of the :contains selector, you can do so by overriding it with a new function like this:

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().replace(/(\n)+/g, " ").indexOf(arg) >= 0;
    };
});

Check out this Fiddle for an example.

This method allows you to keep your existing code intact and simply add in this snippet. However, it's typically not recommended as best practice. You could also rename the custom selector if desired:

$.expr[":"].mycontains

Another example is available in this different Fiddle.

Answer №2

The idea is quite inefficient and so is my response:

$("article").each(function () {
    if ($(this).text().replace(/(\n)+/g, " ") == "A really long text here") {
        // Take action
        $(this).css({color: 'blue'});
    }
});

Keep in mind that the browser interprets a series of whitespace characters as a single space. It might be wise to reconsider your approach.

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

Perform the action when the button is clicked

I'm struggling with finding a solution to this problem. I have an input field and a submit button. My goal is to update the value of a variable to match the value in the input field when the submit button is clicked. Additionally, I need to execute a ...

Display a concealed text box upon clicking BOTH radio buttons as well as a button

Below is the HTML code for two radio buttons and a button: <body> <input data-image="small" type="radio" id="small" name="size" value="20" class="radios1"> <label for=&qu ...

How can we modify the position of a header from fixed to relative when the mobile drop-down menu is opened?

I am experiencing an issue with my responsive design. When viewed on a device that is less than 600px wide, the drop-down multi-level navigation overflows downward and does not scroll because the header has a fixed position. As a result, the tabs in the me ...

Resolving the dilemma of complete form validation in Jquery

I'm currently working on a PHP form that is being validated with jQuery. In this form, there is a radio button list. If the user clicks "Yes," then the textbox related to that radio button should not be validated. However, if the user clicks "No," the ...

How to transform multi-dimensional arrays to JSON format using JavaScript (and maybe jQuery)

Currently facing a Javascript dilemma where data storage is essential in the following format: MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..) The main array consists of ...

Save user input data into an Excel file using PHPExcel

Could someone assist me with storing values from my form inputs to Excel using PHPExcel? I have successfully stored data from my table to Excel, but now I want to store the values from my inputs. Can anyone help me, please? Example of the form inputs: ent ...

Switching back and forth between celsius and fahrenheit using jQuery (my mistake in the code)

I am currently using Ajax to interact with the openweather API. Everything seems to be functioning correctly except for one issue. My goal is to create a button that toggles between displaying temperature in Celsius and Fahrenheit. When I click the button ...

Troubleshooting issues with the 'date' input type feature on mobile devices

When I use the following code: <input type='month' ng-readonly='vm.isReadonly' required min="{{vm.threeMonthsAgo}}" max='{{vm.oneMonthAhead}}'/> I am experiencing some difficulties on mobile devices that do not occur o ...

Having trouble grasping the display property combination in Bootstrap4

Incorporating Bootstrap4 into my web application, I am faced with the task of displaying a menu exclusively on the large screen size setting (lg). The guidelines are straightforward: utilize a class to conceal an element across all screen sizes: .d-none ...

Bootstrap does not control the text family, weight, and line height

Currently, I am practicing adding grid layouts using Bootstrap. I have been trying to change the font styling within my project, but unfortunately, none of the changes seem to be taking effect. It's quite frustrating because even though I'm follo ...

Ways to navigate to a new webpage in JavaScript without the need to click on a link

After going through various posts and trying different methods, I am still facing challenges. In a PHP page, I have an HTML form with an onClick command that triggers a JavaScript validation procedure when the user clicks a button. While everything funct ...

When using JavaScript to dynamically load canvases and create drawing contexts within a function, the context may suddenly disappear

Currently, I am modifying the canvases displayed through ajax calls and also updating what is drawn on each canvas. The primary issue I am facing is that my main drawing function fails on getContext and there are some unusual behaviors such as missing canv ...

Unable to submit form within a while loop in PHP table

After making some changes to my form, I noticed that only the hidden input field is being submitted when I try to submit the form. It's strange because it was working perfectly fine before. while ($row = mysqli_fetch_array($gettimesheets)) { $dat ...

Response received from PHP POST request using Ajax

Here is the ajax code that I am currently using: $.ajax({ url: apiURL, type: 'POST', data: {data:cart}, success: function(response){ console.log(response); }, error: function(error){ throw new Error(' ...

Tips for preventing a page from automatically scrolling to the top after submitting a form

Recently, I set up a form where users can input values. The form is set to submit either on change or when the user hits enter, depending on which value they want to update. However, after the values are submitted, the page automatically jumps back to the ...

Adding jQuery content to a div that is being created dynamically

Currently implementing a save/load feature using JSON for a diagram that utilizes jsPlumb. While the save functionality is working perfectly, the load functionality is encountering difficulties in replicating the full initial saved state. The issue arises ...

Vuetify 3 now displays full text in v-autocomplete without an ellipsis

Trying to truncate long text in a v-autocomplete component using Vuetify 3 and text-overflow: ellipsis, but it's not working. Check out the code below: <div id="app"> <v-app id="inspire"> <v-row align="cen ...

The event.target.x attribute on the <i /> tag element

In my code, there is an <i name="documentId" onClick={this.openDocument}/> element with the onClick method defined as follows: openDocument(event) { const { name } = event.target; console.log('name', name); console.log('target&a ...

Customizing the hover behavior of a div element without causing displacement of surrounding elements

I am facing an issue where the descriptions in my list of 100 items are longer than the width of the div, causing the text to be cut off. I want to display the full description on hover without affecting the layout of other items. Currently, when I hover o ...

Incorrectly colored buttons upon clicking

I am experiencing an issue with my website where the color of the container div is not changing to the correct color when a button representing a color is clicked. Instead, it seems to be displaying the next color in the array of color codes that I have se ...