How to add class to element that contains a certain string which is being pulled from database

I was using the following code to search for a particular piece of text within a div, and if found, to add another class to the div.

<div class="res">Full HD</div>    

$(document).ready(function () {
  $('div.res').each(function () {
    if ($(this).text() === "Full HD") {

It worked great and thank you to this community for helping me figure out how to do that.

However, I am instead pulling the text that I want the function to search for, ie "Full HD", from the database using the following PHP and now it no longer works, as I reluctantly expected.

<div class=\"res\">".$suggested_videos[$i]['definition']."</div>

I sort of understand why this no longer works but have a hard time articulating it so I apologize for that. Is there something I can add to the javascript function to search for "Full HD" within the ['definition'] column of my database and to then add the correct class ('fullhd') based upon if it finds it or not?


So the javascript function I was using was in fact working correctly with the php database and didn't need to be changed at all. The issue was due to me not capitalizing "Full HD" on the database. It was pulling "Full HD" from the database instead of "FULL HD", and thus when searching for "FULL HD", nothing was found, and thus no class was being added. Thank you for the replies and the potential workarounds. It means a lot to know there are people out there willing to help a stranger. I can't wait to give back.

1 answer

  • answered 2018-02-13 00:53 1000Nettles

    Since you are outputting your content via PHP anyhow, you could simply add a conditional on the server / PHP side checking for what $suggested_videos[$i]['definition'] is, and then add the class there. See the following:

    echo '<div class="res ';
    if ($suggested_videos[$i]['definition'] === 'Full HD') {
        echo 'fullhd';
    echo '">' . $suggested_videos[$i]['definition'] .'"</div>';

    Untested but it should lead you down the correct path.

    Some further clarification: your JavaScript runs within the frontend of a website / in a user's browser, and has no direct access to the database. PHP runs on your server (even if it's your local development machine) and will generate the content to be output to the frontend, before the user even sees it. The above checks the content and adds the <div> class if the conditional is correct. This may also be of use to you: