jQuery change child text

前端 未结 5 1335
不知归路
不知归路 2021-01-17 19:51

I have a jquery function that changes a text inside a element using a jquery \"text\" function. Inside this td element is child \"a\" tag like this.

相关标签:
5条回答
  • 2021-01-17 19:55

    If you want to change text in a select menu, you can do this by giving an option an id or class.

         $('selector').children('option[id=option_id]').text('new text');
    
    0 讨论(0)
  • 2021-01-17 20:04

    If you have:

    <td class="v3">
         <a href="somelink">text to change</a>
    </td> 
    

    Then in your function you should have something like this:

    $("td.v3").children("a").text("new text");
    

    However, this will select all links that are direct children of tds with class .v3. Adding a .first() after children should help:

    $("td.v3").children("a").first().text("new text");
    
    0 讨论(0)
  • 2021-01-17 20:06

    Working Code !!

    using child-selector > with pseudo-class :first-child

    const changeIt = () => {
      $('div.v3 > a:first-child').text('New Text');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="v3">
      <a href="somelink">text to change</a>
    </div>
    
    <button onclick="changeIt()">
      Click
    </button>

    0 讨论(0)
  • 2021-01-17 20:08

    Wrap the text in a span element, and change the text in the span.

    <div id="foo">
        <span>bar</span>
        <a href="#">link</a>
    </div>
    
    ...
    
    $('#foo span').text('new text');
    

    Edit:

    Or use $('td.v3 a').text("new text") to change the text in the anchor, if that's what you want to do.

    0 讨论(0)
  • 2021-01-17 20:20

    You would simply change another element's text.

    <td>
       <a href="#">Link</a>
       <span>SomeText</span>
    </td>
    

    Then invoke like so:

    $('td').find('span').text('myNewText');
    
    0 讨论(0)
提交回复
热议问题