简体   繁体   中英

How can I Add a tag in a div

I want to add aa tag in frontpage-course-list div but, the below code will add class in frontpage-course-list div .

    $( "#frontpage-course-list" ).add( "a" ).addClass( "myclass" );
    var pdiv = $( "#frontpage-course-list" ).add( "a" );

Please let me know how to add

Use append

$("#frontpage-course-list").append("<a class='yourclass'></a>");

This will add the anchor as last child of that specified element( frontpage-course-list ).

If you want to add the anchor as firt child, then use prepend

$("#frontpage-course-list").prepend("<a class='yourclass'></a>");

You can also try something like,

var anchor = $("<a/>", {
    'class': 'yourclass',
    'href': 'your href'
});
$("#frontpage-course-list").append(anchor);

You have to use append:

 $( "#frontpage-course-list" ).append("<a class='myclass'>My custom link</a>");

If you want an img inside a you can do

$( "#frontpage-course-list" ).append("<a class='myclass'><img src='/path/to/image'></a>");

Or if you want an image (not a link) you can write the following:

$( "#frontpage-course-list" ).append("<img src='/path/to/image'>");

If you want to create a new anchor element with the said class then add it to the div then you can use

$('<a />', {
    'class': 'myclass'
}).appendTo('#frontpage-course-list')

The .add() will return a jQuery object which contain the elements in the calling set and the elements returned by the passing selector.

The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:

  $( "#frontpage-course-list" ).add( "a" ).addClass( "myclass" );
  var pdiv = $( "#frontpage-course-list" ).add( "a" );// WRONG, pdiv will not change.

To over come this, use .append .

 $("#frontpage-course-list").append("<a class='myclass'></a>");

Reference DOC

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