2

I'm trying to remove the text whatever is present after a particular tag using jquery

My html code is

<div class="myclass">
    <a href="#"></a>
    <a href="#"></a>
    Hey I want to delete this text
</div>

Jquery

$(document).ready(function() {
   $('.myclass').each(function() {
      // Confused here
      $(this).children(':nth-child(3)').text(''); 
   });
});

I guess that there is no 3-rd child in the class. Any ideas would be greatly appreciated.

Nizam Ali
  • 241
  • 2
  • 9
  • 16

5 Answers5

4

You can do:

$(document).ready(function () {
    $('.myclass').each(function () {
        // Confused here
        $(this).contents().filter(function () {
            return this.nodeType === 3 && $.trim(this.nodeValue).length;
        }).replaceWith('');
    });
});

Fiddle Demo

Felix
  • 37,892
  • 8
  • 43
  • 55
1

Fiddle Demo

$(document).ready(function () {
    $('.myclass a:eq(1)')[0].nextSibling.remove();
});


:eq() Selector

Zero-based index of the element to match

$('.myclass a:eq(1)') get second a tag inside element with class myclass

than get it's .nextSibling and .remove()

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

you can do this:

$(document).ready(function() {
  $('.myclass').find('a:last')[0].nextSibling.remove();
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0

Try this:

$(".myclass").contents().filter(function(){ return this.nodeType == 3; }).remove();

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0
$('.myClass').html($('.myClass').html().substring(0,$('.myClass').html().lastIndexOf(">")))

I also came across similar thread. This might help you as well How do I select text nodes with jQuery?

Community
  • 1
  • 1
Faiz Mohamed Haneef
  • 3,418
  • 4
  • 31
  • 41