The target element from which the content begins.

Hi, it seems I have a little problem with some jQuery code, but I can't get it to work,
I want to add content based CSS style starting from 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 code, it should just stylize only the β€œstrong” element.

+5
source share
2 answers

You are not doing anything wrong ...
you just need to create your custom selector :

 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

although you already have a selector :contains ,
Well, this is not the same thing that starts with , but is useful in cases

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

where the Sizzle selector engine does something familiar to many 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; }; }), 
+7
source

Well, jQuery does not start - with a selector for text. You can check what's inside . Css () - using the function as an argument, and with regEx, setting background-color only if there is a match.

 $('p strong').css('background-color', function() { if ($(this).text().trim().match("^1.6")) { return '#3c763d'; } }); 

Check below fragment

 $('p strong').css('background-color', function() { if ($(this).text().trim().match("^1.6")) { return '#3c763d'; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p><strong>1.6.0</strong> this is some content</p> <p><strong>1.6.1</strong> this is some content</p> <p><strong>2.1.6</strong> this is some content</p> <p><strong>6.1.6</strong> this is some content</p> <p><strong>1.6.9</strong> this is some content</p> 
+4
source

All Articles