views:

114

answers:

3

Using JQuery, I can do the following to get the text within my LI

$("#listingTabs li").eq(2).text();

How do I set the text? Because the following doesn't work

$("#listingTabs li").eq(2).text() = 'insert new text';
+3  A: 
$("#listingTabs li").eq(2).text('insert new text');
dionadar
+5  A: 
$("#listingTabs li").eq(2).text("insert new text");

You can also set the innerHTML of the li using

$("#listingTabs li").eq(2).html("<b>insert new text</b>");
Justin Swartsel
+1 for proper formatting, though you answered later.
Tatu Ulmanen
What about --> $("#listingTabs li").eq(2).html('insert new text'); ?
Brettk
Which is better and why?
Brettk
neither is better - they do different things... pick the one that does what you want it to do
dionadar
the text() function will automatically escape HTML tags, so blah.text('<b>boo</b>') will set the text to "<b>boo</b>", whereas if you used blah.html() then you would get "boo" in bold.
Dave
@Dave, I don't understand - can you explain in more detail. That still sounds like you get the same resulting even using a <b> bold tag
Brettk
+4  A: 

The text() function works as both a getter and a setter. Try this:

$("#listingTabs li").eq(2).text('insert new text');

If you give it a parameter, it acts as a setter for that property. If you don't, it acts as a getter.

zombat
What about --> $("#listingTabs li").eq(2).html('insert new text'); ?
Brettk
The `html()` function basically sets and retrieves the `innerHTML` property of an element. There can be subtle differences between `text()` and `html()` for an element, depending on the markup inside the element.
zombat
For an `<li>`, the `html()` and `text()` functions will do the same thing if you just have plain text inside the `<li></li>` tags. If you put markup such as a `<span>` tag in there, you will see differences in the results.
zombat
@zombat, what happens if I have markup inside the insert like "insert <b>bold</b> text". what's the difference now?
Brettk
It's probably taking you longer to type out that question than it would to test it, but if you have markup inside your text string, you need to use the `html()` function to set it.
zombat