-1

To preface this question this isn't a scenario like so many others that are structured like this:

<div>
    <div class="ErrorMessage"></div>
    <div class="ErrorMessage"></div>
    <div class="ErrorMessage"></div>
    <div class="ErrorMessage"></div>
</div>

I know that :first-of-type or :first-child would work for those.

My scenario is when I have the same class being called on multiple elements throughout the DOM but they don't all follow the same structure. For instance I might have this kind of structure at some point in the page.

   <div class="appArea">
      <p class="ErrorMessage">
        Some text to be changed
      </p>
    </div>

    <div class="appArea">
      <div class="something-for-space">
        <p class="ErrorMessage">
          Some text
        </p>
      </div>
    </div>

    <div class="appArea">
      <table class="some-random-table">
        <tr>
           <td>        
             <p class="ErrorMessage">
                Some text
             </p>
           </td>
        </tr>
      </table>
   </div>

My interest lies in how do I select just the first occurrence of the class "ErrorMessage". I need to change it's default text and I've got a jQuery script that is working but it changes the text for every "ErrorMessage". I haven't been able to find the right cocktail of selectors to ensure that only the first is changed.

Fiddle for reference: https://jsfiddle.net/md6f0cb8/41/

Even if I change it for all instances of the class it's not the end of the world. I could just hide the other instances with CSS (the others are all redundant). But again, I don't have the proper selector(s) to ensure only the first occurrence is shown while the others are all hidden.

Any help is greatly appreciated!

1 Answers1

1

What you need is the .eq() jQuery method:

$(document).ready(function() {
  $(".ErrorMessage").eq(0).replaceWith("<span>Erreur : Veuillez vérifier les renseignements   saisis ci-dessous. Certains champs sont obligatoires et d'autres présentent des contraintes de saisie particulières.</span>");
  $(".appArea span:first-of-type").addClass('testing');
});
.testing {
  font-size: 24px;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appArea">
  <p class="ErrorMessage">
    Some text to be changed
  </p><br/><br/>
</div>

<div class="appArea">
  <div class="something-for-space">
    <p class="ErrorMessage">
      Some text to be changed
    </p><br/><br/>
  </div>
</div>

<div class="appArea">
  <div class="someother-random-div">
    <p class="ErrorMessage">
      Some text to be changed
    </p>
  </div>
</div>
tkounenis
  • 665
  • 4
  • 18