jQuery replace text leaving siblings intact

后端 未结 4 1602
清歌不尽
清歌不尽 2020-12-29 10:29

I\'m having trouble wrapping my head around what should be a simple solution. I want to replace text within a label tag, without affecting the other \'siblings\', if they ex

相关标签:
4条回答
  • 2020-12-29 10:51

    As patrick points out, you can use contents() to select the text alone, and then do a replace on it all. Adapting the example given there, you could also try:

    $(".myFieldsetClass label:contains('Some Label ')").contents().filter(function() {
      return this.nodeType == 3 && $(this).is(":contains('Some Label ')");
    })
    .replaceWith("Some Label");
    

    However, if you know that "Some Label " will always be the last element in the <label> then patrick's method will be faster I believe.

    0 讨论(0)
  • 2020-12-29 10:52

    A one-liner:

    $('.myFieldsetClass label').contents().last().remove().end().first().after('New Label')
    
    0 讨论(0)
  • 2020-12-29 10:54

    Why not simply do an entire replace using regex?

    $(".myFieldsetClass label:contains('Some Label ')")
        .each(function() {
                $(this).html($(this).html().replace(/Some Label ./, "Some Label")); 
            });
    
    0 讨论(0)
  • 2020-12-29 11:01

    Try:

    $(".myFieldsetClass label:contains('Some Label ')").contents().filter(':last-child').text("Some Label");
    

    This should work assuming the text to be replaced will always be at the end. The contents() function selects all nodes, including text nodes.

    http://api.jquery.com/contents/

    EDIT: I should have used filter() instead of find(). Corrected.

    EDIT: Works now. Here's one way.

    // Store proper labels in a variable for quick and accurate reference
    var $labelCollection = $(".myFieldsetClass label:contains('Some Label ')");
    
    // Call contents(), grab the last one and remove() it
    $labelCollection.each(function() {
        $(this).contents().last().remove()
    });
    
    // Then simply append() to the label whatever text you wanted.
    $labelCollection.append('some text')
    
    0 讨论(0)
提交回复
热议问题