开发者

JQuery unwrap content

Within a CMS I am working on a blog. The HTML structure of the output for each post title looks like this:

<h2>
    <a href="...">Title</a>
</h2>

What I want to do is remove the <a>开发者_如何学JAVA tag that wraps the content representing the blog title.

I did a bit of looking around and found 2 almost-solutions:

  1. remove() - this will remove the content itself too though
  2. unwrap() - I don't think you can target text within a tag with this to get rid of the tag itself.


Use .wrapInner first and unwrap the new structure..

$('h2 a').wrapInner('<span>').children().unwrap();

Demo at http://jsfiddle.net/gaby/ffKDn/


Updating with a better way ..

Use the .contents() to target the text nodes and use .unwrap() on those..

$('h2 a').contents().unwrap();

Demo at http://jsfiddle.net/gaby/ffKDn/8/


This would be achieved much more efficiently by editing the appropriate template within the CMS. But you can accomplish it with the following.

$(document).ready(function() {
    $('h2').each(function() {
       $(this).html($(this).children().html());
    });
});

See this JSFiddle example.


You can use remove() but first you need to capture the text. So something like this

var title = $('h2 a').text();
//grab the text from the a href

$('h2').remove('a');
//remove the link    

$('h2').html(title);
//add the title back to the h2

Example: http://jsfiddle.net/qzHsb/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜