I know you can use :contains to get elements who's innerHTML contains a certain string, but how can I get the elements whos innerHTML starts with a string?
+4
A:
Using a filter function you can filter based on any criteria that you'd like:
var spans = $("span").filter(function(idx) {
return this.innerHTML.indexOf(myString) == 0;
});
joshperry
2010-09-02 21:03:30
No need to wrap things :) `this.innerHTML` works, and is much less expensive as well.
Nick Craver
2010-09-02 21:04:38
right-o Nick, thanks.
joshperry
2010-09-02 21:24:10
A:
You could do something like this:
<!doctype HTML>
<html>
<head>
<script type = "text/javascript" language = "JavaScript" src = "jquery-1.4.2.min.js"></script>
<script type = "text/javascript" language = "JavaScript">
var elems;
$(document).ready(function(){
$("div").each(function(){
var content = $(this).html();
if (content.match(/asdf/)){
alert(content);
}
});
});
</script>
</head>
<body>
<div>asdfaowhguiwehgiuh</div>
<div>asdfaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>asdfaowhguiwehgiuh</div>
</body>
</html>
In order to find whether it's in the content at all..if you want the first few characters you should split the content on those characters and test just it.
akellehe
2010-09-02 21:07:08
A:
The filter method will let you compare an element's content, and then you can do whatever you like (in this case, I've done addClass('selected')
).
$('p').filter(function() {
var searchString = 'Blue';
return ($(this).html().substring(0, searchString.length) == searchString);
}).addClass('selected');
Demo:
Justin Russell
2010-09-02 21:07:09