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!
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.
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.
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.
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.
Try something like this :
$("div#preload h2").html("Some Text Here")
See the above code in action for your sample HTML here
$("#preload h2").text('WOOt Woot');
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With