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');
});
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');
});
Share
Improve this question
asked May 24, 2013 at 1:15
ojhawkinsojhawkins
3,28816 gold badges53 silver badges69 bronze badges
3 Answers
Reset to default 10Maybe 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.
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.
Change:
this.html('foo');
to:
$(this).html('foo');
You're attempting to use a jQuery method on a non-jQuery object. This of course assumes that your table cells have the class .leg-number
.