jQuery add text to span within a div

Jquery

Jquery Problem Overview


<div id="tagscloud">
       <span></span>
</div>

How would I do to add some text within the span like code below ?

<span>**tag cloud**</span>

Edit: actually the span has an id

<div id="tagscloud"> <span id="WebPartCaptionWPQ2"></span> </div>

Jquery Solutions


Solution 1 - Jquery

You can use:

$("#tagscloud span").text("Your text here");

The same code will also work for the second case. You could also use:

$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");

Solution 2 - Jquery

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

Solution 3 - Jquery

You can use append or prepend

> The .append() method inserts the > specified content as the last child of > each element in the jQuery collection > (To insert it as the first child, use > .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser472285View Question on Stackoverflow
Solution 1 - JquerykgiannakakisView Answer on Stackoverflow
Solution 2 - JqueryScarabeetleView Answer on Stackoverflow
Solution 3 - JqueryAnwar ChandraView Answer on Stackoverflow