How to set the text node value using jQuery

11,865

Solution 1

put it in a span

<div class="votes">
    <b>5</b> <span id="votesTxt">Votes</span>
    <a id="vote-' + element_id +'" href="#" class="vote-btn"></a>
</div>

and then

$("#votesTxt").text(( newCount == '1' ) ? 'Vote' : 'Votes');


EDIT if you don't wish to use span then just change the text for the element after the b tag:

$("#votes b:first")[0].nextSibling.data = (( newCount == '1' ) ? 'Vote' : 'Votes');

Solution 2

As you have seen, jQuery is not really made for handling text nodes. Your var voteTextNode will be a jQuery instance, holding a set of text nodes. You can hardly manipulate them using .text(), which would add some new TextNodes into them.

Yet, this should work:

 $(this).parent('div').contents().each(function() {
     // iterate over all child nodes
     if (this.nodeType == 3)
        this.data = "Vote";
 });

But with plain dom methods it may be clearer:

 var countTextNode, voteTextNode;
 $(this).parent('div').find('b').each(function() {
      countTextNode = this.firstChild;
      voteTextNode = this.nextSibling;
 });
 return function setVotes(num) {
      countTextNode.data = num;
      votTextNode.data = num == 1 ? 'Vote' : 'Votes';
 };

Solution 3

Treat it as the DOM tree it is: what you probably want is to get the first <b> element inside each <div> with class "votes" and then change the text in the text node that immediately follows it. jQuery is good at selecting and iterating over elements so use it for this part if you want. Once you've got the <b> elements, switch to regular DOM. Here's an example:

Demo: http://jsfiddle.net/Qq3T7/

Code:

$("div.votes").find("b:first").each(function() {
    this.nextSibling.data = ($(this).text() == "1") ? " Vote" : " Votes";
});
Share:
11,865
Code Prank
Author by

Code Prank

Updated on June 04, 2022

Comments

  • Code Prank
    Code Prank almost 2 years

    I have a HTML structure like this:

    <div class="votes">
        <b>5</b> Votes
        <a id="vote-' + element_id +'" href="#" class="vote-btn"></a>
    </div>
    

    I have manage to get the text after 5 i.e. votes using:

    var voteTextNode = $(this).parent('div').contents().filter(function() {
                        return this.nodeType == 3;  
                    });
    var voteText = voteTextNode.text();
    

    now i want to change this text to vote which is respective number of votes . I have tried this:

    voteNewText = ( newCount == '1' ) ? 'Vote' : 'Votes';
    voteTextNode.text(voteNewText);
    

    but it does not work for me. I have also tried the code from this link: How can I get, manipulate and replace a text node using jQuery? but it also wont work for me tell me where i am doing wrong