Find element which contain text with parentheses

151 Views Asked by At

I have html site and I want to find element using text with parentheses. For example I have divs with spans like this:

#container
 .div
   %span= "example (1)"
 .div
   %span= "example (22)"

I want to get span with text "example (22)". I have method I use to get those elements. I tried following solutions:

 getElement: (title, count) =>
   #title = 'example', count = 22
   # First try
   $("#container span:contains(#{title} (#{count})")
   # Second try
   filter = new RegExp(title+"//("+count+"//)") 
   $("#container span").filter (i, el) ->                     
                                     return !!$(el).text().match(filter)

But I found nothing. How to improve my method? Thanks for all answers.

1

There are 1 best solutions below

0
On
getElement = (title, count) ->
  spans = document.querySelectorAll '#container span'
  filter = Array.prototype.filter
  filter.call spans, (span)->
    text = span.textContent.trim()
    text is "#{title} (#{count})"

element = getElement "example", 22
console.log element[0]?.textContent

I have no idea why you try to do with RegExp. If you need some pattern, it could be. but that's heavy. if you want to match a text with static string, just compare via == in JavaScript, is in CoffeeScript. Above source is written with vanilla not jQuery, but I think it's enough for what I wanna say.