view raw
user2513528 user2513528 - 1 year ago 46
Javascript Question

Target element which content starts-with

Hi I seem to be having a little issue with some jQuery code but I cant seem to get it to work,

I want to add CSS style based on the content starting with


<p><strong>1.6.1</strong> this is some content</p>

jQuery as follows:

$('p strong:starts-with(1.6)').css('background-color', '#3c763d');

based on the code it should just style the 'strong' element only.


You're not doing anything wrong...
you just need to build your custom selector extension:

jQuery.extend(jQuery.expr[':'], { 
  "starts-with" : function(el, i, p, n) {    
     // return el.textContent.startsWith(p[3]); // ES6 (Thanks @Adeneo :)
     return (el.textContent || el.innerText).indexOf(p[3]) === 0;

$('p strong:starts-with(1.6)').css('background-color', '#3c763d');  
<script src=""></script>
<p><strong>1.6.1</strong> this is some content</p>

though you already have available the :contains selector,
Well, it's not the same as starts-with but is useful in cases

$('p strong:contains(1.6)').css('background-color', '#3c763d');  

where the Sizzle selector engine does something already accustomed for the variety of browsers in the wild

"contains": markFunction(function( text ) {
  text = text.replace( runescape, funescape );
  return function( elem ) {
    return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;