4

yes, agree that I should have figured this out from the doc, but no - I could not :-(

<div id="jalla">
    <span>
        <span class="ui-btn-text">
            I need this text
            <span class="ui-collapsible-heading-status">
                click to collapse contents
            </span>
        </span>
    <span>
</div>

How to simply select (and update) the text "I need this text". This is one of the things I've tried:

notWorking = $('.ui-btn-text').text();
Larsi
  • 4,654
  • 7
  • 46
  • 75
  • 3
    Duplicate of [this question](http://stackoverflow.com/questions/3268556/javascript-select-only-text-of-an-element-not-its-children). Is also the first result on [google](https://www.google.com/search?q=select+only+text+of+element). – Chad Nov 22 '11 at 18:32
  • 2
    I formatted your code and it seems you are missing a `` or have one `` too much. You might want to correct that. – Felix Kling Nov 22 '11 at 18:34
  • @Phrogz he is asking to get the first text only element, which is what that question is. Besides this question being a `span`, and the other a `td` they are the same. Both questions are manipulating the text of embedded elements. – Chad Nov 22 '11 at 18:38
  • @Chad - Sorry, should have found that. Thanks for providing the link – Larsi Nov 22 '11 at 18:44
  • @FelixKling - Thanks for formatting and pointing out. Now corrected. – Larsi Nov 22 '11 at 18:50

1 Answers1

4

Sometimes jQuery is not the best answer. In this case the HTML DOM makes it easier.

var span = document.querySelector('.ui-btn-text'); // first item with this class
var text = span.childNodes[0];                     // an actual text node
text.nodeValue = "Changed!"                        // done!

Seen in action: http://jsfiddle.net/C7Q6K/

Edit: For older browsers, you could use jQuery to get the span itself:

var span = $('.ui-btn-text')[0];  // get the DOM element, not the jQuery object
span.childNodes[0].nodeValue = "Changed!";
Phrogz
  • 296,393
  • 112
  • 651
  • 745