Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append text inside of an existing paragraph tag

Tags:

I am trying to add additional text to the end of a paragraph using jQuery. My thought was to produce a structure like this:

Judging by my answers I will clarify. I need to create this structure first. And this is the part that I find difficult, not the second end result. So how do I dynamically create this:

<p>old-dynamic-text<span id="add_here"></span></p>

And then after adding the new text it would look like this:

<p>old-dynamic-text<span id="add_here">new-dynamic-text</span></p>

I've been playing with the .wrapAll() method, but I can't quite get the desired effect. Is this the best way to do this (and if so how), or is there another way to append new text to the end of an existing paragraph (that needs to be wrapped in some type of tag since I need to style it differently)?

like image 556
sage88 Avatar asked Apr 25 '13 03:04

sage88


People also ask

How do you put text inside a tag?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.

How do you append something in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How append a div in another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.

What is the correct syntax to insert content after the div elements?

The jQuery after() method is used to insert content after the selected elements.


4 Answers

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

like image 182
msapkal Avatar answered Oct 05 '22 02:10

msapkal


Try this

$('#add_here').text('new-dynamic-text');
like image 33
Jude Duran Avatar answered Oct 05 '22 00:10

Jude Duran


If you want to append text or html to span then you can do it as below.

$('p span#add_here').append('text goes here');

append will add text to span tag at the end.

to replace entire text or html inside of span you can use .text() or .html()

like image 40
Dipesh Parmar Avatar answered Oct 05 '22 00:10

Dipesh Parmar


I have just discovered a way to append text and its working fine at least.

 var text = 'Put any text here';
 $('#text').append(text);

You can change text according to your need.

Hope this helps.

like image 35
طلحة Avatar answered Oct 05 '22 02:10

طلحة