简体   繁体   中英

How to append an <i> tag to an <a> tag using jquery

I am trying to append an tag for an icon to an tag using JQuery.

This is the code for how I am trying to append it:

$loginLink = $('ul.nav li:eq(2) a');
$loginLink.append("<i class='icon -login' aria-hidden='true'></i>");

For some reason, it does not work :(

JQuery is new to me so any help will be greatly appreciated.

Thanks.

Here you have a working fiddle :

http://jsfiddle.net/LDvTX/

<ul class="nav">
    <li><a>list item 1</a></li>
    <li><a>list item 2</a></li>
    <li><a>list item 3</a></li>
    <li><a>list item 4</a></li>
    <li><a>list item 5</a></li>
</ul>

$loginLink = $('ul.nav li:eq(2) a');
$loginLink.append("<i class='icon -login' aria-hidden='true'>HERE</i>");

Try to do something like this:

 $loginLink = $('ul.nav li:eq(2) a');
 $($loginLink).append("<i class='icon -login' aria-hidden='true'></i>");

This should work.

Try this :

$loginLink = $('ul.nav li:eq(2) a');
alert($loginLink.length); // must be different from 0 (just to be sure your selector is matching a dom element)

$newElement = $("<i>").html("myText")
                      .prop("aria-hidden","true")
                      .addClass("icon")
                      .addClass("-login") ;
$loginLink.append($newElement);

The point is to create a new dom element using $newElement = $('<i>') . After that you add properties and class as you want. Finally, you append it to the container $loginLink .

Creating a new element let you remove it later if you need :

$newElement.detach(); // detach from dom, but still existing and can be re-appended.

or

$newElement.remove(); // detach and delete the element.

EDIT : you can also use the short method :

$loginLink.append($("<i>").html("myText")
                          .prop("aria-hidden","true")
                          .addClass("icon")
                          .addClass("-login")
                 );

Are the

  • tags previously dynamically generated ? What fire the actions ?

  • 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