jQuery - setting an element's text only without removing other element (anchor)

前端 未结 3 1662
时光说笑
时光说笑 2020-12-08 10:00

I have an element like this:


  anchor
  [ some text ]

And i need to set it\'s text in jQuery, wit

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 10:23

    Neal's answer is my suggestion. jQuery doesn't have a way to select text nodes How do I select text nodes with jQuery?.

    Changing your HTML structure will make for the simplest code. If you can't do it, you can just use the childNodes property looking for nodes of type 3 (TEXT_NODE)

    Here's some sample code that assumes the last node is the node you want to edit. This is a better approach than replacing the entire contents of the td because you could lose event handlers when you recreate the HTML

    $('a').click(() => console.log(' was clicked'))
    
    $('#btn').click(() =>
      $('.someClass').get(0).lastChild.nodeValue = " New Value");
    
    
    anchor [ some text ]

提交回复
热议问题