Change <div> to <a>
I am a novice jQuery student and need a bit of help. Is it possible for Jquery to change a <div>
to an <a>
dynamically depending on what the class of the <div>
is? I have searched and can't find any reference to doing something like this using .add(), .append() or .htm开发者_如何学Pythonl()
For example I want to change this:
"<div class="item"><div class="caption">pic1</div></div>"
to this:
"<a class="item" href="#"><div class="caption">pic1</div></a>"
Thanks for any help you may give or advice. Mike
You can try jQuery.replaceWith()
. You will probably want to use that in conjunction with jQuery.get()
.
Another option would be to use the manipulation functions to get the children of your tag, unwrap the tag, and then wrap the children with the desired tag.
jQuery('.item').children().unwrap().wrap('<a></a>');
However, as Andy pointed out in the comments, a div
cannot exist inside of an a
tag. That is not semantically correct HTML. What benefit are you trying to derive from doing this?
Edit: I saw you changed your question as I was updating my answer. Seems like you'd be better off with doing something like this instead (Different version mentioned by Silkster):
jQuery(document).delegate('.item', 'click', function (e) { /* Do something here */ });
jQuery.delegate()
So, yeah, it is possible ... you should be able to use a selector by class like:
$('div.item')
... to the update using the replaceWith() like:
$('div.item').replaceWith('<a class='item'></a>');
... and then for the content you can just get the content and updated later using the each function like:
$('div.item').each(function (){
var divContent = $(this).html();
$(this).replaceWith('<a class='item'></a>').html(divContent);
});
I would suggest you check out jQuery wrap and unwrap They should be able to do what you like.
精彩评论