简体   繁体   中英

How to remove specific text from HTML

I want to eliminate first 5 links (complete <a>...</a> ). Also ALL of the pipes ("|").

<p> | <a href="/node/1">link 1</a>  
    | <a href="/node/2">link 2</a>  
    | <a href="/node/3">link 3</a> 
    | <a href="/node/4">link 4</a> 
    | <a href="/node/5">link 5</a> 
    | <a href="/node/6">link 6</a>  </p>

This is what I have so far:

$(".main p a:lt(4)").hide();

REVISION 1 ------

getting closer I think with this-

$('.main p a').html( $('.main p a').html().replace(/|/gi,'') );

REVISED 2 ------

Here is what finally worked for me thanks to your great ideas! the hi:contains helps to ensure that it won't start defacing all my pages.

   if($('h1:contains("some specific text")')){
        $(".main p a:lt(4)").hide();
        $('.main p').html($('.main p').html().replace(/\|/g, ''));
    }    

Try

$(".main p a:lt(4)").hide();

$('.main p').contents().filter(function(){
    return this.nodeType == 3 && $.trim($(this).text()) == '|';
}).remove();

Demo: Fiddle

to remove all the '|' pipes

$("p").html().replace(/\|/g,"");

or

$("p").html($("p").html().replace(/\|/g,""));

If you need to remove a single link,

$("p a").eq(1).remove();

To remove first 5 links,

$("p a:lt(5)").remove();

See the fiddle: http://jsfiddle.net/Te6ad/

This will replace the bars.

$('p').html($('p').html().replace(/\|/g, ''));

to replace bars.

JS fiddle: http://jsfiddle.net/gjWSc/1/

I don't understand what links you wanted removed though..

According to my understanding of your question,following is the answer to your question:

Html code:

<p> 
    | <a id="1" href="/node/1" class="link">link 1</a>  
    | <a id="2" href="/node/2" class="link">link 2</a>  
    | <a id="3" href="/node/3" class="link">link 3</a> 
    | <a id="4" href="/node/4" class="link">link 4</a> 
    | <a id="5" href="/node/5" class="link">link 5</a> 
    | <a id="6" href="/node/6" class="link">link 6</a>  

</p>

Script:

<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script>
    var i = 0;
    $('.link').each(function () {
        var id = $(this).attr('id');
        $('p').html($('p').html().replace('|', ''));
        $('#' + id).hide();
        if(i==3)
        {
            return false;
        }
        i++;
    });
</script>

Please correct me if I am wrong...

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