Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add text to specific div element using jQuery?

I am having a problem with jquery. My HTML is

<div id="first">
   <span class="test"></span>
</div>
<div id="second">
   <span class="test"></span>
<div> 

Now I am trying to add text in span using Jquery.

$j('span.test').text('Welcome');

After that it becomes,

<div id="first">
    <span class="test">Welcome</span>
</div>
<div id="second">
    <span class="test">Welcome</span>
<div> 

But, I am tryting to achieve is,

<div id="first">
    <span class="test">Welcome</span>
</div>
<div id="second">
    <span class="test"></span>
<div>

How can I do that in jquery?

like image 216
user1311776 Avatar asked Jan 11 '13 12:01

user1311776


2 Answers

Several possible alternatives

Others have provided their answers already but let me give you some more alternatives.

$("span.test:first").text("Welcome");
$("#first span.test").text("Welcome");
$("span.test").first().text("Welcome");
$("span.test").eq(0).text("Welcome");
$("span.test", "#first").text("Welcome");

The second and last one likely being the fastest because they target particular container by ID.
(internal jQuery optimisations may prove me wrong with any future version)

Performance comparison

Here's a JSPerf test that performance compares upper possibilities. As anticipated, the second and last approaches are the fastest of all because element selection is much simplified. I've tried running them on Chrome and you may run them in other browsers if you want to and see differences.

like image 59
Robert Koritnik Avatar answered Oct 05 '22 19:10

Robert Koritnik


$('#first span.test').text('Welcome');

jQuery selectors are CSS selectors extended with a bit of magic. You can find everything you need to know here: http://api.jquery.com/category/selectors/

like image 31
Milimetric Avatar answered Oct 05 '22 18:10

Milimetric