Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add some text using jQuery

I'm using jQuery, I have a div with H2 tags

<div id="preload"><h2></h2></div>

I would like to know how to use jQuery to add a text within the <h2> tags

Final result should be:

<div id="preload"><h2>Some text here</h2></div>

I need to add the text without replacing the tags <h2></h2> in the jQuery script.

Any ideas? Many thanks!

like image 925
GibboK Avatar asked Aug 01 '12 19:08

GibboK


People also ask

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How do I get paragraph text in jQuery?

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.

What is append in jQuery?

jQuery append() Method The 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 do you add elements?

Add Several New Elements With append() and prepend() However, both the append() and prepend() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the examples above), with jQuery, or with JavaScript code and DOM elements.


3 Answers

Try something like this :

$("div#preload h2").html("Some Text Here")

See the above code in action for your sample HTML here

like image 175
Ashutosh Jindal Avatar answered Oct 30 '22 17:10

Ashutosh Jindal


$("#preload h2").text('WOOt Woot');
like image 25
Vinit Avatar answered Oct 30 '22 17:10

Vinit


Use .text

$("#preload h2").text("Some text here");

Also not that this must be within either $(document).ready(function () { ... }) or $(function () { ... }). I would use the latter as it saves typing.

$(function () {
    $("#preload h2").text("Some text here");
});
like image 24
Austin Avatar answered Oct 30 '22 17:10

Austin