Jeppe Christensen Jeppe Christensen - 9 months ago 24
jQuery Question

Determine if li element contains specific text

I have a

<li>
element in which text is being appended from a controller. If the text is: "Email already exists." i want to append a link otherwise, i dont want to append anything.

I have the following function in jQuery, but it just doesn't work:

if ($("#validat ul li").indexOf("Email") >= 0)
{
$("#validat ul li").append("<a href='@Url.Action("ForgotPassword","Auth")'>Forgot password?</a>");
}


What am i missing?

Answer Source

Use .each() method. Details are commented in Snippet.

SNIPPET

/* Each list item do this... */
$('#validat ul li').each(function() {

  /* If the <li> has text content of 
  || "You got Mail"...
  */
  if ($(this).text() === "You got Mail") {
    /* append() a link within that <li> is 
    || the last child
    */
    $(this).append("<a href='#somewhere'>Click Here</a>");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="validat">
  <ul>
    <li>You got Mail</li>
    <li>You got Mail</li>
    <li>You got Mail</li>
    <li></li>
    <li>You got Mail</li>
    <li>You got Mail</li>
    <li></li>
    <li>You got Mail</li>
    <li>You got Mail</li>
    <li>You got Mail</li>
    <li></li>
    <li>You got Mail</li>
    <li></li>
    <li></li>
    <li>You got Mail</li>
    <li>You got Mail</li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li>You got Mail</li>
    <li>You got Mail</li>
    <li></li>
    <li>You got Mail</li>
  </ul>