Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 1.6:

<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.

like image 735
user2513528 Avatar asked Apr 28 '16 21:04

user2513528


1 Answers

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
     return (el.textContent || el.innerText).indexOf(p[3]) === 0;
  }
});


$('p strong:starts-with(1.6)').css('background-color', '#3c763d');  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><strong>1.6.1</strong> this is some content</p>

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexof https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

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;
  };
}),
like image 132
Roko C. Buljan Avatar answered Sep 28 '22 04:09

Roko C. Buljan