How to change only text node in element

前端 未结 8 775
不知归路
不知归路 2020-11-28 10:40

I have next html:


And I want to chang

相关标签:
8条回答
  • 2020-11-28 10:43

    you can use replace accomplish this

      var html = $('label[for=user_name]').html().replace('Name','Testing');
      $('label[for=user_name]').html(html);
    

    check it : http://jsfiddle.net/DyzMJ/

    0 讨论(0)
  • 2020-11-28 10:46

    Sorry for the late reply... But here is a way to do so using only jQuery:

    $('label').contents().last().replaceWith('Title');
    
    0 讨论(0)
  • 2020-11-28 10:48

    It may not be the prettiest way, but this works:

    var $label = $('label[for=user_name]');
    $label.html($label.html().replace("Name", "Title"));
    
    0 讨论(0)
  • 2020-11-28 10:51

    Evans solution added to jquery fn to make it's use comfortable:

    // get/change node content not children
    jQuery.fn.content = function( n ){
        var o = $(this).clone();
        var c = o.children().remove();
        if (typeof n === "string" ){
            o.html(n);
            $(this).html(c).append(n);
        }
        return o.html();
    }
    

    Usage :$('myselector').content('NewContentString');

    0 讨论(0)
  • 2020-11-28 10:54

    If you use contents() method it will also return text nodes. Since jQuery doesn't have text node methods, convert last node to a DOM node

    $('label[for="user_name"]').contents().last()[0].textContent='Title';
    

    Demo: http://jsfiddle.net/yPAST/1/

    0 讨论(0)
  • 2020-11-28 10:56

    if you are manipulating more than 1 label you can select each label and replace text with jquery:

    $('label[for="user_name"]').contents().last().replaceWith("Title");
    

    and for the second label :

    $('label[for="user_lastname"]').contents().last().replaceWith("Title2");
    

    and so on ...

    0 讨论(0)
提交回复
热议问题