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

Updating database tables by incorporating jquery and mysql via php

I'm struggling with updating the selected item from a list populated using php and updated with jquery. Here's what I have so far: This is my update.php front-end code <?php include_once('db.php'); ?> <!DOCTYPE html PUBLIC " ...

gh-pages: Images that should not be cached

Every time my build server completes a new build, it automatically uploads a pass/fail graphic to the gh-pages branch. I'm looking to showcase this graphic on my project's page. Unfortunately, it appears that gh-pages is caching the image. Any s ...

Show the result of (Firstname) on the thank you page after the form has been submitted

Need help with a PHP issue; it seems simple but I'm uncertain of the correct method, whether through jQuery or PHP. I have a contact form where I want certain field results to display on the thank you page after submitting the form: Thank you for en ...

Having a newline between HTML elements can disrupt the structure of an HTML layout

It's common knowledge that in html, a newline between elements is treated as space. However, I find it quite alarming when working on responsive layouts. For instance, take a look at this example where the expected and correct behavior is achieved on ...

Change to a dark theme using React hooks in typescript

Hello, I am new to React and English is not my first language, so please excuse any mistakes. I have been trying to enable a dark mode feature on my website. Most examples I have found involve toggling between dark and light modes where you need to specify ...

Scrolling in iOS 8 causing flickering problem with background image

Utilizing the Supersized jQuery slider plugin to create a full-page background slider with a fade-in effect and added height for scrolling. The slider functions correctly on desktop, but upon testing on an iOS 8 iPad device, there is noticeable flickering ...

Tips for adjusting your Navbar from transparent to solid based on screen size changes instead of scrolling

I am seeking assistance in creating a responsive Navbar that transitions from transparent to solid when the screen size changes, such as on a smartphone. I want the Navbar to remain fixed at the top of the page and not move down as I scroll. I tried adding ...

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...

Switching between various quantities of inputs in each row using Bootstrap V3

My Bootstrap V3 form has a mix of rows with two inputs and rows with one input, as per the designer's request. Check out my fiddle here: https://jsfiddle.net/06qk4wh4/ <div class="form-group col-sm-12"> <label class="control-label col- ...

In MUI React, the opacity of the placeholder is customizable and can be easily adjusted. This allows for the placeholder to be hidden

Currently, I am facing an issue with a filled variant TextField from Mui React. I have tried to modify it using theme components, but the placeholder text becomes hidden when the field is not focused. See here for Before Focus And here for On Focus I hav ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

Tips on utilizing browser scroll for horizontal overflow of internal div?

I'm working on creating a dynamic page with a tree-like structure that easily exceeds the width of the browser window. My goal is to enable horizontal scrolling for the entire page using the browser's scrollbar, without needing a separate scrollb ...

Maintaining alignment between the site content and the navbar items is a key feature of Bootstrap

I am struggling to align the brand and dropdown menu on the right with the content of my page. My goal is to have a single column for the content, taking up col-8 on larger devices and col-12 on smaller devices. I want the navbar and footer to always be 10 ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...

Ways to conceal a div using ng-hide

Is there a way to make a div disappear using ng-hide? I have this code and I'm trying to hide the div with id="ApagarNA". The code displays a table with values, but some rows contain N.A in all 4 columns, and I want to hide those specific rows. For e ...

How to align the last item in the bottom row using Flexbox styling

Is it possible to center the last element when resizing the window to a smaller resolution, even though the parent's justify-content parameter is set to space-between? I understand that using center or space-around would achieve the desired result, bu ...

Check out the source code of the file causing the redirection

Whenever I click on a URL, it triggers a redirect using the window.location function. I am curious to examine the code within this HTML file. Unfortunately, as it is constantly redirecting, I am finding it difficult to access the source code. Is there a w ...

Using the AJAX post method to generate a JSON object from database results and send it back to a jQuery UI Dialog

I wrote a script that loads sample images from the database based on the relevant category when the page loads. Here's a simplified version of the PHP script: <?php $category = 'granite'; $samples = 'SELECT * FROM material WHERE ma ...

Attaching an input text box to an Angular $scope is not possible

In my angular app, I have a piece of markup that showcases a table with saved queries. Each query has the option to add a title using an input field. When you click the edit icon, it should display the newly created title. <table class="table table-str ...

Is there a way to address this scrollbar issue without relying on HTML?

Currently, I am working on a website where the only customization allowed is related to CSS. While I've been able to make progress, I've encountered an issue with the scrollbar placement. The scrollbar is extending beyond the boundaries of the di ...