Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Search a string and it's element (JavaScript)

<tr>
   <td> <p> Bobby </p>  </td>
   <td> <p> Love   </p>  </td>
   <td> <p> Fat     </p>  </td>
   <td> <p> Cat    </p>  </td>  
<tr>

I want to search "Bobby" in my html document. If i found that i need all other table data (td) value in return as a string (Bobby Love Fat Cat). How can i do that in JavaScript using a function ?

Using jQuery or pure JavaScript?

1 Answer

This is the way I solved it:

Example: Codepen

Code:

function findStringInElementContent(nodeList, str) {

  // Element's content
  var txt = '';
  // Create Regular Expression to search
  var re = new RegExp(str, 'g');
  // String is found boolean
  var isFound = false;

  // Loop thru each Node in the NodeList
  for (var el = 0; el < nodeList.length; el++) {
    // Store the inner HTML of a Node on each pass
    txt = (nodeList[el].innerText !== undefined) ? nodeList[el].innerText : nodeList[el].textContent;

    // String is found
    if(re.test(txt)) {
      // Change string's color
      nodeList[el].style.color = 'orange';
      isFound = true;
    }
  }

  // Return isFound
  return isFound;
}

// NodeList of all td elements
var elList = document.getElementsByTagName('td');
// String to search for
var searchStr = 'Bobby';

// Call function
var isStrFound = findStringInElementContent(elList, searchStr);