最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery hide inner html, except for a tags - Stack Overflow

programmeradmin2浏览0评论

I have the following HTML:

<div class="content-body attribute-pdf">
<a href="/_fragment/content/download/296/1935/file/blabla.pdf">
blabla.pdf</a> 1.2 Mb
</div>

This is ing out of a CMS, and I would like to hide this "1.2 MB",but still keep the A href part

is this possible to do in jQuery ?

I tried this:

$(".attribute-pdf").children().hide(); 

which hides the A href, but still shows the text. I want it vice-versa - hide the text, but still show the A href.

I have the following HTML:

<div class="content-body attribute-pdf">
<a href="/_fragment/content/download/296/1935/file/blabla.pdf">
blabla.pdf</a> 1.2 Mb
</div>

This is ing out of a CMS, and I would like to hide this "1.2 MB",but still keep the A href part

is this possible to do in jQuery ?

I tried this:

$(".attribute-pdf").children().hide(); 

which hides the A href, but still shows the text. I want it vice-versa - hide the text, but still show the A href.

Share Improve this question asked Jun 12, 2014 at 15:29 Danny HoboDanny Hobo 6941 gold badge7 silver badges25 bronze badges 1
  • or pletely remove the text is also not a problem – Danny Hobo Commented Jun 12, 2014 at 15:32
Add a ment  | 

6 Answers 6

Reset to default 4

A quick way, in jQuery - empty the div, replace its contents with just the <a> tag:

$('.attribute-pdf').each(
  function() {
    var container = $(this);
    var a = container.find('a').detach();
    container.empty().append(a);   
  }
); 

Example: http://codepen.io/paulroub/pen/iaFnK

You could set the contents of the parent to be the contents of the childeren ...

$(".attribute-pdf").each(function(){
    var $this = $(this); // cache for performance
    $this.html($this.children());
});

grab the content ( a link ) , empty the div ( removes 1.2 mb ) and again append a link.

http://jsfiddle/vpVMK/

    var content = $(".attribute-pdf a");
    $(".attribute-pdf").html(''); 
    $(".attribute-pdf").append(content);

you could do:

// contents() gives children, all including non-element nodes.
// Then, we can filter those down to the final text one.
var textNodes = $( ".attribute-pdf" ).contents().filter(function() { 
    return this.nodeType === 3; 
});

var lastTextNode = textNodes.last();
//and replace 
lastTextNode.replaceWith('');

You could do this:

var children = $(".attribute-pdf").children();
$(".attribute-pdf").html(children);

http://jsfiddle/H2WVt/

Here is another method that hasn't been posted yet:

$(".attribute-pdf").html(function(){
    var $this = $(this),
        $tmp = $('<div>');

    return $.makeArray( $this.children('a').map(function() {
        $tmp.html(this)
        return $tmp[0].innerHTML
    }) ).join('')
})

The fiddle

发布评论

评论列表(0)

  1. 暂无评论