2

Here's what I've got:

<div id="fivearea">Something</div>

Then later:

var 5popup= $('#fivearea').text();

This makes 5popup = "Something".

However, I want to add some more text to what's in the div and save that as a variable. Psuedo-code:

var 5popup= $('#fivearea').text()+"some additional text";

What's the correct way to do this?

jonmrich
  • 4,233
  • 5
  • 42
  • 94
  • 1
    Your pseudocode is fine as is. Just use that. Except that variable names can't begin with a number. – gilly3 Mar 26 '15 at 00:47

3 Answers3

2

You will want to add to the current value of the variable like this:

    5popup += "some additional text";
Full Stack Alien
  • 11,244
  • 1
  • 24
  • 37
1

Replacing the text inside the node below:

<div id="testId">hello</div>

Can be accomplished as follows

$("#testId").html("good bye");

Resulting in the html:

<div id="testId">good bye</div>

Similarly the text inside the node can be saved to a variable as follows:

var myTest = $("#testId").html();

If you want to add to the text inside a node without deleting anything, this can be accomplished with the append function. Given the following html.

<div id="testId">hello</div>

The code:

$("#testId").append(" world");

Will result in the html:

<div id="testId">hello world</div>
Ben Pearce
  • 6,884
  • 18
  • 70
  • 127
  • I read the question as asking how to get a variable whose value is the text from some div, plus some extra text. I don't see where in the question he is asking how to change the text in the div. – gilly3 Mar 26 '15 at 00:56
  • He didn't accept my answer so I expect your right. However I interpret "I want to add some more text to what's in the div" as needing to append to the DOM element. – Ben Pearce Mar 26 '15 at 01:52
0

I think this is what you want:

var text = $('#fivearea').text();
text += "Your text here";
$('#fivearea').text(text);

If you want to access the text, use the variable text. Hope this helped.