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.
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;
};
}),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With