简体   繁体   中英

How to wrap a link around a div jQuery?

The code below should a user to click on a button of which he is prompted for a URL. Once a URL is entered, a new i element is created with a link to the inputted URL wrapped around it as an a tag.

The code works however the link tag isn't created - how do I go about doing this?

The new link should be wrapped around that specific div only.

Thanks.

<script type="text/javascript">
    $(function() {
      $(".twitter_new").click(function() {
          link = prompt("Paste a url");
          if (link == null) {
          return;
          }
          else {
          div = document.createElement('i');
          $(div).addClass("fa").addClass("fa-twitter").wrapAll('<a href="' + link + '"></a>');
          $(".icons").append(div);
          }
        });
    });
</script>

Your wrapAll() expression doesn't modify what the variable div is. It returns a new object.

You are still appending the original i element only

I would suggest you create 2 elements or do this all as html string

// create `<i>`
var $i = $('<i>',{class: 'fa fa-twitter'});
// create <a> and append <i>
var $a = $('<a>', {href:link}).append($i);
// append complete <a> to dom
$(".icons").append($a);

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