Home > OS >  jQuery selector is wrong on removeAttr
jQuery selector is wrong on removeAttr

Time:01-23

I try to remove all ids from a certain class, then to put id on a new element on click on a link that has a class but it's not working.

The add of the new id seems to work but the removing of all ids before adding this new id is not working.

This is my code :

$(".response").click(function () {
//    $('.responsediv').find("input[type=text], textarea").val("");
    $('.blogcommentresponse-form').removeAttr('id')
    $(".responsediv").fadeOut();
    $(this).parents("div").next(".responsediv").css("visibility", "").fadeIn(100);
    $(this).parents("div").next(".responsediv").closest(".blogcommentresponse-form").attr('id','blogcommentresponse-form');
});

It works fine for adding id to the new form element but not for removing id of all others forms.

Maybe I'm thinking the click function does not work with the selector of a class that is outside of this selector.

The code where it should apply on my blog:

<div >
  <div >
    <h2 >
      Commentaires sur cet article
    </h2>
  </div>
  <div > <img loading="lazy"  src="assets/img/team/face-6.png" alt="">
    <div >
      <div >
        <div >
          <h5 >Gérard Ricard</h5> <span >15 janvier 2022 à 00:05</span>
        </div>
        <div > <a  style="cursor:pointer">Répondre</a> </div>
      </div>
      <p>Bonjour, que préconisez-vous pour le renforcement de vieux murs en bauges ?
        Par avance merci </p>
      <ul >
        <li >
          Note :
          <i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i>
        </li>
      </ul>
    </div>
  </div>
  <div  style="display:none">
    <div ></div>
    <div >
      <div >
        <h3 >
          Publier une réponse au commentaire de Gérard Ricard
        </h3>
      </div>
      <form action="plugins/skyforms/blog-comment-response-process.php" method="post"  novalidate="novalidate"> <input type="hidden" name="id_article" value="103"> <input type="hidden" name="face_id" value="4"> <input type="hidden" name="id_comment" value="119">
        <fieldset>
          <div >
            <div > <input type="hidden" name="blogcommentresponse"> <label  for="bon_blog_commentresponse_name">Votre nom :</label> <input  placeholder="Nom ou Pseudo" type="text" name="nom_blog_commentresponse" required=""> </div>
            <div > <label  for="bon_blog_commentresponse_email">Votre e-mail :</label> <input  placeholder="Adresse e-mail" type="email" name="email_blog_commentresponse" required=""> </div>
          </div>
          <div > <label  for="commentaire_blog_commentresponse">Votre commentaire :</label> <textarea  name="commentaire_blog_commentresponse" rows="5" placeholder="Tapez votre commentaire ici" minlength="30" maxlength="500" required=""></textarea>
            Caractères restant : <span >500 caractères</span> </div>
          <p><button type="submit" ><i ></i> Envoyer votre commentaire</button></p>
        </fieldset>
      </form>
      <div >
        <div ></div>
        <div  role="alert"> <button type="button"  data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div > <span > <i ></i> </span> <span > <strong>Terminé !</strong> Votre réponse a bien été envoyée. Elle est en attente de modération.
            </span> </div>
        </div>
        <div  role="alert"> <button type="button"  data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div > <span > <i ></i> </span> <span > <strong>Attention !</strong> A cause d'une erreur technique, le commentaire n'a pas pu être envoyé. Veuillez recommencer plus tard.
            </span> </div>
        </div>
      </div>
    </div>
    <div ><br> <span style="cursor:pointer ;color:#000000 !important" >X</span> </div>
  </div>
  <div > <img loading="lazy"  src="assets/img/team/face-99.png" alt="">
    <div >
      <div >
        <div >
          <h5 >Stan Piotrowski</h5> <span >16 janvier 2022 à 21:27</span>
        </div>
      </div>
      <p>Bonjour,
        l'idéal est d'utiliser des croix de chaînages reliées avec des tirants. Toutefois vous pouvez aussi réaliser un chaînage traditionnel avec une structure armée. Veillez a bien utiliser un mortier de scellement à retrait compensé afin de s'adapter aux propriétés de dilatation de la terre.</p>
    </div>
  </div>
  <div > <img loading="lazy"  src="assets/img/team/face-5.png" alt="">
    <div >
      <div >
        <div >
          <h5 >Smith</h5> <span >14 janvier 2022 à 08:02</span>
        </div>
        <div > <a  style="cursor:pointer">Répondre</a> </div>
      </div>
      <p>Bonjour,
        dans quelle mesure est-il possible de faire un traitement étanchéité sur des murs semi-enterrés ?
      </p>
      <ul >
        <li >
          Note :
          <i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i><i  style="color:#4765a0;font-size: 14px"></i>
        </li>
      </ul>
    </div>
  </div>
  <div  style="display:none">
    <div ></div>
    <div >
      <div >
        <h3 >
          Publier une réponse au commentaire de Smith
        </h3>
      </div>
      <form action="plugins/skyforms/blog-comment-response-process.php" method="post"  novalidate="novalidate"> <input type="hidden" name="id_article" value="103"> <input type="hidden" name="face_id" value="4"> <input type="hidden" name="id_comment" value="117">
        <fieldset>
          <div >
            <div > <input type="hidden" name="blogcommentresponse"> <label  for="bon_blog_commentresponse_name">Votre nom :</label> <input  placeholder="Nom ou Pseudo" type="text" name="nom_blog_commentresponse" required=""> </div>
            <div > <label  for="bon_blog_commentresponse_email">Votre e-mail :</label> <input  placeholder="Adresse e-mail" type="email" name="email_blog_commentresponse" required=""> </div>
          </div>
          <div > <label  for="commentaire_blog_commentresponse">Votre commentaire :</label> <textarea  name="commentaire_blog_commentresponse" rows="5" placeholder="Tapez votre commentaire ici" minlength="30" maxlength="500" required=""></textarea>
            Caractères restant : <span >500 caractères</span> </div>
          <p><button type="submit" ><i ></i> Envoyer votre commentaire</button></p>
        </fieldset>
      </form>
      <div >
        <div ></div>
        <div  role="alert"> <button type="button"  data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div > <span > <i ></i> </span> <span > <strong>Terminé !</strong> Votre réponse a bien été envoyée. Elle est en attente de modération.
            </span> </div>
        </div>
        <div  role="alert"> <button type="button"  data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
          <div > <span > <i ></i> </span> <span > <strong>Attention !</strong> A cause d'une erreur technique, le commentaire n'a pas pu être envoyé. Veuillez recommencer plus tard.
            </span> </div>
        </div>
      </div>
    </div>
    <div ><br> <span style="cursor:pointer ;color:#000000 !important" >X</span> </div>
  </div>
  <div > <img loading="lazy"  src="assets/img/team/face-99.png" alt="">
    <div >
      <div >
        <div >
          <h5 >Stan Piotrowski</h5> <span >14 janvier 2022 à 17:00</span>
        </div>
      </div>
      <p>Bonjour, il existe toutes sortes de procédés pour le traitement des parties enterrées : cuvelage, drainage, revêtement bitumineux. Tout dépend de la configuration de votre maison ainsi que du type d'infiltrations que vous avez.
        Bien cordialement, l'équipe SP-BATIMENT</p>
    </div>
  </div>
</div>

Any kind of advice will be much appreciated.

CodePudding user response:

I think you maybe mixed up your question a little - your code removes the ids fine, but it does not add them. Here's a JSFiddle of your code - I added an id to each form so you can see what happens. Clicking the links removes the ids fine, but adding an id does not work.

Adding wasn't working simply because you're traversing in the wrong direction. You're using .closest() on the matched .responsediv, but that searches its ancestors up through the DOM. The .blogcommentresponse-form that you're searching for is a child of .responsediv, so you need to search down through its descendants. You can do that with .find().

Working snippet:

$(".response").click(function () {
    $('.blogcommentresponse-form').removeAttr('id')
    $(".responsediv").fadeOut();
    $(this).parents("div").next(".responsediv").css("visibility", "").fadeIn(100);

    // Changed .closest() to .find() here
    $(this).parents("div").next(".responsediv")
        .find(".blogcommentresponse-form")
        .attr('id','blogcommentresponse-form');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    
  <div >
    <div >
      <div>
        <div >
            <!-- LINK 1 ################################################### -->
            <a >Répondre</a>
        </div>
      </div>
      <p>Bonjour, que préconisez-vous pour le renforcement de vieux murs en bauges ? Par avance merci </p>
    </div>
  </div>

  <div  style="display:none">
    <div >
      <!-- FORM 1 ################################################### -->
      <!-- Give form an ID so we can check if it is removed/updated -->
      <form  id="form-1">Form 1</form>
    </div>
  </div>

  <div ></div>

  <div >
    <div >
      <div>
        <div >
            <!-- LINK 2 ################################################### -->
            <a >Répondre 2</a>
        </div>
      </div>
      <p>Bonjour, dans quelle mesure est-il possible de faire un traitement étanchéité sur des murs semi-enterrés ?</p>
    </div>
  </div>

  <div  style="display:none">
    <div >
      <!-- FORM 2 ################################################### -->
      <!-- Give form an ID so we can check if it is removed/updated -->
      <form  id="form-2">Form 2</form>
    </div>
  </div>

  <div ></div>

</div>

Side note 1: Please try to make a minimal, complete, and verifiable example when posting a question. 90% of the time I spent on this question was simply trying to get down to the basic structure of your HTML. The code you've added so cluttered with CSS classes and unrelated HTML that it obscures what we - and you! - really need to see and focus on to get a feeling for the problem. The snippet I added is what I boiled it down to; starting from something like that the problem is almost immediately obvious.

Side note 2: as already pointed out in the comments, dynamic IDs seem semantically like the wrong appoach. IDs are supposed to be unique, specific elements, not something that changes. I'd suggest maybe using a class, eg .active, to identify the "active" form.

Side note 3: I'm not sure how much control you have over the HTML, maybe it is autogenerated by a plugin, but this is much harder, and IMO more brittle and liable to break, because the semantically related element groups are not grouped together under a parent. If each link and form were nested in a parent element, this would be much easier, and less likely to break if elements are changed or moved around in some future updates. Eg:

<div >
    <div >
        <a ></a>
    </div>

    <div >
       <form ></form>
    </div>
</div>

Now the code to find the form is simple:

$('.response').on('click', function() {
    // Find the form
    $(this).closest('.comment').find('.blogcommentresponse-form')...

CodePudding user response:

I have edit your on click function to version that can find the form and add id that you want. The line that i comment was not able to find form so next line of your code i have adden new line. it makes exacly what do you want to do.

$(".response").click(function () { 
  $('.blogcommentresponse-form').removeAttr('id')
  $(".responsediv").fadeOut();
  $(this).parents("div").next(".responsediv").css("visibility", "").fadeIn(100);
  // $(this).parents("div").next(".responsediv").closest(".blogcommentresponse-form").attr('id','blogcommentresponse-formid'); //this code can't find the form 
  $(this).closest('.media').next(".responsediv").find(".blogcommentresponse-form").attr('id','blogcommentresponse-formid');// Right way to add id atribute
});
  •  Tags:  
  • Related