简体   繁体   中英

Clone anchor tag link with text in div

 $( ".post-title > a" ).clone().prependTo( ".post-text" ).text("View More");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <div class="post-text"> <div class="post-title"> <a href="https://www.google.com/">Google</a> </div> </div> <div class="post-text"> <div class="post-title"> <a href="https://www.yahoo.com/">Yahoo</a> </div> </div> <div class="post-text"> <div class="post-title"> <a href="https://www.msn.com/">MSN</a> </div> </div>

I want to show new text 'View More' with same link in the div. Now it is showing all links in same div with 'View More' text.

The problem is that you are prepending your cloned element to each .post-text element. So every .post-text will have all cloned elements.

Create a function that runs through each .post-title element.

 $('.post-title').each(function () { $(this).find('> a').clone().prependTo($(this).closest('.post-text')).text('View more'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <div class="post-text"> <div class="post-title"> <a href="https://www.google.com/">Google</a> </div> </div> <div class="post-text"> <div class="post-title"> <a href="https://www.yahoo.com/">Yahoo</a> </div> </div> <div class="post-text"> <div class="post-title"> <a href="https://www.msn.com/">MSN</a> </div> </div>

You have to just loop through using class post-text and pick nested child element using .find() function and apply logic.

 //$( ".post-title > a" ).clone().prependTo( ".post-text" ).text("View More"); $('.post-text').each(function(i, obj) { var postTitleElem = $(this).find(".post-title > a"); console.log(postTitleElem); $(postTitleElem).clone().prependTo(this).text("View More"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <div class="post-text" > <div class="post-title"> <a href="https://www.google.com/" >Google</a> </div> </div> <div class="post-text"> <div class="post-title"> <a href="https://www.yahoo.com/">Yahoo</a> </div> </div> <div class="post-text"> <div class="post-title"> <a href="https://www.msn.com/">MSN</a> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM