Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery each replace innerHtml

Jquery

I am trying to change the inner text on multiple td element which I believe should look something like this although this does not appear to be a jquery object when I am debugging (I could be wrong).

What is the correct way this should be done?

$('.leg-number').each(function () {
        this.html('foo');
    });
like image 932
ojhawkins Avatar asked Feb 23 '26 12:02

ojhawkins


2 Answers

Maybe try this instead:

$('.leg-number').html('foo');

which is a shorter and more efficient way to achieve your goal. It is just asking jQuery to set the inner html of every element with class "leg-number" to "foo" without any explicit iteration. Most of the jQuery methods like .html() can work on sets of elements so you don't really need to use .each() for simple cases like this.

Now on why your version didn't work: Using .each() would work if you wrapped this with the jQuery function $() so you could use the jQuery methods on it:

$('.leg-number').each(function () {
    $(this).html('foo');
});

The variable this inside of the .each() callback is a DOM element and you need $(this) to convert it into a jQuery object that wraps this element. See the explanation in the answer by epascarello who explained it before I updated my answer.

like image 57
rsp Avatar answered Feb 26 '26 02:02

rsp


Read the docs for each(). this is a DOM Html Element node, not a jQuery object reference. You can either convert it back to jQuery or use innerHTML directly.

$(this).html('foo');

or

this.innerHTML = 'foo';

The docs show using $(this) in the examples.

like image 23
epascarello Avatar answered Feb 26 '26 02:02

epascarello