2

For the following code:

<div myLable="a"><p><span style="color:#00aaFF">change me only 1</span></p></div>
<div myLable="b"><span style="color:#00aaFF">change me only 2</span></div>

If I use

$('div[myLable="a"]').text("change");
$('div[myLable="b"]').text("change");

Then all the html code inside will be change, it was not what I need.

Note that there are two pre-condition:

  1. No any label or id in the child element.
  2. We've no idea how deep the child element in, what can conclude is that the requirement is to change the most deepest child element's text.
  3. It will be good if using raw javascript in solution, but must use the $('div[myLable="a"]') form because the parent element has no id but only a user-define label, so I need this Jquery form.

How can I change the text only in this case?

Thanks in advance,

Wa

Sampson
  • 265,109
  • 74
  • 539
  • 565
user1232236
  • 207
  • 1
  • 4
  • 10
  • 1
    If you know your text will always be wrapped inside a `span` then give a specific `class` to the `span` and change text inside it. – Bongs May 08 '12 at 04:55
  • 2
    ["Select deepest child in jQuery"](http://stackoverflow.com/questions/3787924/select-deepest-child-in-jquery) – Sampson May 08 '12 at 05:02
  • 1
    Thank you and sorry, I'm new here and don't know to accept answer, will accept valid answer from now on. – user1232236 May 08 '12 at 05:04

2 Answers2

3

You need to change the text inside of span. So use apropriate selector which point to span:

$('div[myLable="a"] span').text("change");
Samich
  • 29,157
  • 6
  • 68
  • 77
0
var $target = $('div[myLable="a"]').children();
$next = $target;

while( $next.length ) {
  $target = $next;
  $next = $next.children();
}

$target.text("change");
meYnot
  • 343
  • 2
  • 6
  • 13