JQuery this.html () returns undefined

I will reformat some really bad HTML using jQuery. I need to combine sibling <font> elements together. I tried this code:

 $('font+font').each(function() { this.html().appendTo( this.prev() ); this.remove(); }); 

but he gave me this error: TypeError: 'undefined' is not a function (evaluating "this.html ()")


Here is an example HTML:

<font>This fragment </font><font>is actually one element.</font>


Update

I updated my code with $(this) , but it still doesn't work. When i run this code

 $('font+font').each(function() { $(this).html().appendTo( $(this).prev() ); $(this).remove(); }); 

I get this error: TypeError: 'undefined' is not a function (evaluation "$ (this) .html (). AppendTo ($ (this) .prev ()) ')

+4
source share
5 answers
  • this must be wrapped in a jQuery object before you can use jQuery methods on it.
  • .html() returns a string. You cannot use jQuery methods for a string without wrapping. Use $this.prev().append( $this.html() ) .
  • When using $(this) more than once, it makes sense to store $(this) in a temporary variable. This is a convention for prefixing jQuery dollar signs.

the code:

 $('font+font').each(function() { var $this = $(this); $this.prev().append( $this.html() ); $this.remove(); }); 
+14
source

When you use each statement, it returns this as a DOM element, not a jQuery object. .html() must be called in a jQuery object. So, the first part of your fix is ​​to convert this to a jQuery element with the $ symbol.

 $(this).html(); //don't use this.html(); 

The second problem is that html() returns a string. You cannot call AppendTo() on a string, only a jQuery object. Since you are working with .html() , I assume that you need the contents of the string, not the full contents. If so, Rob's answer is more appropriate.

 this.textContent = $(this).prev().html() + this.textContent; // prepend siblings content 

The final code is as follows:

 $('font+font').each(function() { this.textContent = $(this).prev().html() + this.textContent; $(this).prev().remove(); }); 

http://jsfiddle.net/b6vLL37k/1

+8
source

You need to use $(this) for jQuery to help you.

+2
source

You need to use $(this) not this

+2
source

I could not fix your code. How about something like this:

  var text = ''; $('font').each(function() { text += $(this).text(); }); console.log($('<p />').text(text)); 
0
source

Source: https://habr.com/ru/post/1395679/


All Articles