Search code examples
javascriptjqueryhtmlcontainsstartswith

If text or value starts with a character, run function


I need to detect if the text in a span BEGINS WITH the letter "x" and run a function. I read I can do it with "^" in strings - but having trouble making it work checking text...

 <span>xfoo</span>
if ($('span:contains(^"x")').length > 0) {
    alert ('there is text on this page starts with x');
}

Bonus points of I can also check the value of an input field...


Solution

  • You've to iterate over all the <span> elements, check the condition and run the code. Use text() to get the textContent of the element and trim() to remove leading and trailing spaces.

    $('span').each(function() {
        if ($(this).text().trim().startsWith('x')) {
            alert('Check this span, it starts with x');
    
            // Use `$(this)` here to refer to the current <span>
        }
    });
    

    If there are many <span> elements in DOM, :contains() can be used to select only the elements having some string(x).

    $('span:contains("x")').each(function() {
        ...