June 11, 2013

use jQuery/jQuerymobile .text to set content of multiple id's

Chris’s Question:

I have a page with multiple page(s- data-roles), and want to set the content on div’s, or other elements. Basically this works… like this:

<a href="..something" id="content-something"></a>
<div id="content-sometext"></div>

and setting it with that:

$('#content-something').text('Something in there');
$('#content-sometext').text('Sometext in there');

The problem occurs when I try to set the content over multiple instances of the id’s, and only the first id is being set – whether in the same page- data role or not:

<a href="..something" id="content-something"></a> ---> Something in there
<div id="content-sometext"></div> ---> Sometext in there
Some more html...
<a href="..something" id="content-something"></a> ---> empty!
<div id="content-sometext"></div> ---> empty!

As far as I understood the jQuery/mobile documentation, multiple instances should be able to be set with .text().

What am I doing wrong?
Thanks a lot for your help in advance 🙂

That is an expected behavior as IDs are suppose to be unique. Use class name to replace text of multiple elements.

<a href="..something" class="content-something"></a>
<div class="content-sometext"></div>
Some more html...
<a href="..something" class="content-something"></a>]
<div class="content-sometext"></div>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!