2

I am talking about a span arranged this way -

 <span class="x">
  <span class="y"></span> my text
 </span>

Is there a way to change this text without wrapping it inside another tag?

Rohan
  • 3,296
  • 2
  • 32
  • 35

4 Answers4

1

Something like this :

document.getElementsByClassName('y')[0].nextSibling.nodeValue = 'some other text';

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Could there be a jquery specific solution for this? – Rohan Jan 26 '14 at 16:13
  • Why would you need a jQuery specific solution when there's an easy way to do it without jQuery? jQuery doesn't really work well with rogue nodes, just with elements, so using the native methods, such as `nextSibling`, is easier. – adeneo Jan 26 '14 at 16:16
  • I wasn't aware about Jquery's inefficiencies when it comes to text nodes though. Will use your answer, please confirm once that the jquery specific answer I cooked up should be second choice just to be sure. – Rohan Jan 26 '14 at 16:22
  • 1
    @themosquitokiller - The jQuery answer you posted should work fine as well, but the native javascript above should work in all browsers and it's short and concise, so there's no point in using jQuery when you don't have to, but that's up to you. – adeneo Jan 26 '14 at 16:34
1

Your question has been asked and answered before. Check this.

The JQuery solution to your question is :

$('.x').get(0).lastChild.nodeValue = " some-text-2";.

But anyhow, here's the full answer:

HTML

<div class='x'>
  <span class='y'></span>
  some-text-1

JS

  $('.x').get(0).lastChild.nodeValue = " some-text-2";

Fiddle.

Community
  • 1
  • 1
Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38
0

If you want to change a comment using jQuery, you will need to use .contents() and look at the node-type 8 for comment.

simbabque
  • 53,749
  • 8
  • 73
  • 136
0

This is one more Jquery based answer apart from the native javascript solution from adeneo.

$(".x").contents().filter(function() {
  return this.nodeType == 3;
}).text('blah');
Rohan
  • 3,296
  • 2
  • 32
  • 35