Search HTML For String Using jQuery

16 May 2013

We recently ran into an issue where we had a eight tags from a JSP that each populated a <div> based on a string from a database. Some of the strings sent "null", meaning that the box should be hidden as no content was delivered. A validation for this would normally be easily written on the server side, but we were sending this content through a web service call to a client's portal. In other words, our goal was to populate a single HTML string and sent it to the client, so once the content was populated we would no longer have any control over the page. This meant that all of our validations for the null content had to be done on the client side once the user opened the document in the portal.

The HTML doc would look something like this:

<div class = "box" id = "box_1">
  <h1><<<box1_head>></h1>
  <p><<box1_copy>></p>
</div>

<div class = "box" id = "box_2">
  <h1><<<box2_head>></h1>
  <p><<box2_copy>></p>
</div>

<div class = "box" id = "box_3">
  <h1><<<box3_head>></h1>
  <p><<box3_copy>></p>
</div>

etc...

To handle this, I used jQuery to search through each of the <div>s after it the content had been populated, looking for a "null" string. Once it was found, the whole thing should be hidden using the jQuery .css() method.

$('.box').filter(function() {
  return this.innerHTML.indexOf("null") !== -1;
}).css("display","none");

I used the filter function returns the position of the string the first place it occurs in the document. According to the jQuery API,

Given a jQuery object that represents a set of DOM elements, the .filter() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result.

We can use indexOf() since we only need "null" to display once to know that the entire block should be hidden, and the indexOf() method only returns the first occurance anyway.