Home > Enterprise >  Prevent auto duplicate append html
Prevent auto duplicate append html

Time:11-24

I am trying to append HTML in multiple divs using classes. But my code is duplicating HTML in one section (HTML 1) when the another is all right.

HTML 1:

<div >
  <div >
    This is a author bio. <a href="https://example.com">example</a><a href="https://example.com">example</a>
  </div>
</div>

HTML 2:

<div >
  <div >
    This is a author bio. <a href="https://example.com">example</a><a href="https://example.com">example</a>
  </div>
</div>

JavaScript:

$(".about-author .author-text,.author-info .author-bio").each(function () {
    var $this = $(this),
        link = $this.find("a");
    link.each(function () {
        var $this = $(this),
            cls = $this.text().trim(),
            url = $this.attr("href");
        $this.replaceWith('<li ><a href="'   url   '" title="'   cls   '" rel="noopener noreferrer" target="_blank"/></li>')
    });
    if (link.length) {
        $this.parent().append('<ul ></ul>');
    }
    $this.find("li").appendTo(".author-links")
});

I want the same output in HTML 1 and HTML 2

CodePudding user response:

You can directly loop through the links..With this way no need to check for length because the loop will not work without <a> found in the divs

I believe there're some ways to do this but that's what it comes in my mind right now .. Check the next code

$(".author-text a,.author-bio a").each(function () {
    var $this = $(this);
    cls = $this.text().trim(),
    url = $this.attr("href");
    newLI = '<li ><a href="'   url   '" title="'   cls   '" rel="noopener noreferrer" target="_blank">'  cls  '</a></li>';
    if(!$this.parent().find('.author-links').length){ // check to not append ul twice
      $this.closest('div').append('<ul ></ul>'); // append the url
    }
    $this.parent().find(".author-links").append(newLI); // append the new li to the url
    $this.remove();  // remove the $this <a> element
});
.author-links{
  background : #d2d2d2;
  padding : 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    This is a author bio 1. 
    <a href="https://example.com">example 1</a>
    <a href="https://example.com">example 2</a>
  </div>
</div>
<div >
  <div >
    This is a author bio 2. 
    <a href="https://example.com">example 3</a>
    <a href="https://example.com">example 4</a>
    <a href="https://example.com">example 5</a>
  </div>
</div>

  • Related