64
<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>

3 Answers 3

142

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");
Sign up to request clarification or add additional context in comments.

4 Comments

yes but i need to take into account the div id also, because i have other span with the same id on this page.
@user472285 Elements shouldn't have the same IDs as each other - IDs on a page should be unique.
i know :( but i have no control on that. the developer made it this way...is there a way to target a span id within a div with an id?
You should try to get them to fix this as duplicate ID can create a very messy situation, at least notify them that the page is broken ;)
20

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.

Comments

18

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.