views:

56

answers:

3

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
No need to wrap things :) `this.innerHTML` works, and is much less expensive as well.
Nick Craver
right-o Nick, thanks.
joshperry
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
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:

http://jsbin.com/ironi/2

Justin Russell