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;
};
}),
Well, there is no jQuery starts-with selector for text. You can check that inside .css() -using function as argument, and with regEx, setting the background-color
only if there's a match.
$('p strong').css('background-color', function() {
if ($(this).text().trim().match("^1.6")) {
return '#3c763d';
}
});
Check the below snippet
$('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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.