Search code examples
jqueryhtmlformsequalscontains

JQuery Contains vs Equals


I have a form and I need help to modify this statement to be equals, not contains:

$('<h2>Basic Information</h2>').insertBefore($('h3:contains("Field1")').parent().parent());

Thanks as always-


Solution

  • If you want to find the h3 that has exactly that text you can use a jquery filter function. Basically you search through all h3 and find just the ones that have just that word as their text. Also use trim() so you clear the white spaces

    Here are 2 solutions.

    you can add your other .parent() ) selectors. ALso there could be a more elegant solution to select it's parent. But without knowing your HTML i cannot help you with that. Share your HTML if you need further assistance

    $('<h2>Basic Information</h2>').insertBefore($("h3")
      .filter((i, heading) => $(heading).text().trim() === "Field1"))
    
    
    // on multiple lines
    
    // var heading = $("h3")
    //  .filter((i, heading) => $(heading).text().trim() === "Field1")
    // $('<h2>Basic Information</h2>').insertBefore($(heading))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <h3>
      Field1
    </h3>
    <h3>
      Field1 2
    </h3>
    <h3>
      Field1
    </h3>