-1

I'm making a chrome extension and i want to do an action when a certain element exist on the page. But the class element isn't precise enough to select the element only by it's class.

the element i'm looking for on pages is the following :

<span class="btn-text">M'y emmener</span>

I tried :

const listfull = document.querySelector('.btn-text:contains("m\'y emmener")');
if (listfull) {
    console.log("hello")
}

But it doesn't seems to work anybody could tell me how this works ?

  • `:conatains()` is jQuery selector. As you're using JavaScript, you need to create a method and filter the elements based on the content. Check the answer to the linked question. – Tushar Jan 14 '20 at 07:00

1 Answers1

1

:contains is jQuery-specific syntax. It's also case-sensitive. To achieve what you're looking for, either use jQuery and capitalize the M:

const listfull = $(`.btn-text:contains("M'y emmener")`);
if (listfull.length) {
    console.log("hello")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="btn-text">M'y emmener</span>

Or iterate over all matches of .btn-text and check their textContent:

const listfull = [...document.querySelectorAll(`.btn-text`)]
  .find(elm => elm.textContent.includes("M'y emmener"));
if (listfull) {
    console.log("hello")
}
<span class="btn-text">M'y emmener</span>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320