سؤال

I want to change the text inside a li. But this li has got an img. Here the html:

<div>
<ul>
<li><b><img src="../../../Images/folder1/image1.png">Text1</b><i>0</i></li>
<li><b><img src="../../../Images/folder1/image2.png">Text2</b><i>1</i></li>
<li><b><img src="../../../Images/folder1/image3.png">Text3</b><i>2</i></li>
<li><b><img src="../../../Images/folder1/image4.png">Text4</b><i>3</i></li>
<li><b><img src="../../../Images/folder1/image5.png">Text5</b><i>4</i></li>
</ul>
</div>

I am trying this:

$("li").each(function () {
$(this).text(sometext);
})

But it is replacing all, including the img. I only want to change the text: Text1,Text2,...

Any ideas?

Thanks!

هل كانت مفيدة؟

المحلول

To get to the textnodes within an element you need to use contents() and then filter() by nodeType. You can then use replaceWith() to change the text. Try this:

$('li:first b').contents().filter(function() {
    return this.nodeType == 3;
}).replaceWith('foo');

Example fiddle

I obviously hard-coded this to use the first li element, but you can change the selector as needed.

نصائح أخرى

You could also do it like this:

http://jsfiddle.net/YNLXQ/

$("li b").each(function () {
   this.childNodes[1].textContent = "32323";
})

Store the image in a separate variable and after replacing the text prepend the image back.

$("li b").each(function () {
    var $img = $(this).find('img'); 
    $(this).text(sometext).prepend($img);
})
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top