Jquery each replace innerHtml - javascript

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');
});

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.

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.

Related

Hook jQuery methods on JavaScript selected elements

Easier to explain with simple code:
$("#element").fadeOut(); // jQuery; works as expected
I want to use .fadeOut() and select element with JS like this:
document.getElementById("element").fadeOut(); // Does not work
How do I make this work and is there any point of doing this (performance wise)?
Any thought is appreciated. Thanks.
You can assign the fadeOut property name to HTMLElement.prototype, and call jQuery's fadeOut from inside it:
// $("#element").fadeOut(); // jQuery; works as expected
HTMLElement.prototype.fadeOut = function(...args) {
$(this).fadeOut(...args);
}
document.getElementById('element').fadeOut();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element">text</div>
That said, overwriting built-in objects like HTMLElement is pretty bad practice and can cause problems - it would be better to just do what you were doing originally, and call .fadeOut on a jQuery object containing the desired element(s).
You can wrap the element in $():
$(document.getElementById("element")).fadeOut();
However, you may find it's easier just to use the jQuery ID selector #:
$('#element').fadeOut();
If you want to use JQuery features, you need to use $() to call the method i.e. fadeout(). See JQuery Selector.
Now that if you want to do it in vanilla JavaScript then check this out.

dynamically added input element doesn't return value in script

After adding dynamically input element (with class "dateValidation") inside static div ( with class "workItems") I use this to provide onclick function:
$(".workItems").on("click", ".dateValidation", function()
{...});
and when I in function above run f.e
alert(this);
I get: [object HTMLInputElement] (I think it's good)
but, when I run:
alert(this.val());
alert(this.hasClass("dateValidation"));
Nothing happens. What is wrong with this code? How Can I get f.e value of this input element?
this is a DOM element, you need to convert it to jquery element before running jquery functions on it
alert($(this).val());
alert($(this).hasClass("dateValidation"));
Use $(this).val() and $(this).hasClass("dateValidation"); instead of this.
this is the DOM object, whereas $(this) is the jQuery wrapper.
Using this, you can call DOM methods/attributes but not jQuery methods. And when using $(this), you can call jQuery methods not DOM methods.
In your case you're trying to access the jQuery method val() using DOM object this which is wrong. So you've to use jQuery methods using jQuery wrapper $(this).
Updated script would be like this.
alert($(this).val());
alert($(this).hasClass("dateValidation"));
Hope this will help to you find issue !!

Is exists way to combine creation of html element and appening to target?

I often see code like:
var element = document.createElement('div');
$(element).appendTo([other element here]);
Is exists way to combine these two operations? And write something like:
[other element here].createElement('div');
Yes.
$(element).append('<div id="myNewElement"></div>')
You can use:
$('div').appendTo([other element here]);
Seems you're looking for:
$otherElement.append(document.createElement('div'));
Or have jQuery create the div
$otherElement.append($('<div />'));
In the above examples $otherElement is your existing jQuery object. Replace with a selector if needed e.g $('#otherElement').
Seeing as you tagged the question with jQuery, yes jQuery has the append() and appendTo() functions.
Using append() :
$(element).append('<div></div>');
Using appendTo() :
$('<div></div>').appendTo(element);

What does jQuery's removeClass method return?

I am confused about these lines of JQuery:
if ($(ui).hasClass("color1"))
$(ui).removeClass("color1").addClass("color2")
else
$(ui).removeClass("color2").addClass("color1")
in this code.
I know that $(ui) is creating a JQuery instance. I would like to know if
.hasClass is testing the entire DOM tree of the JQuery instance for
any element which has color1 as part of its class attributes.
Also, the docs for
removeClass do not state what
removeClass returns. They do so allegorically with this code:
$("p").removeClass("myClass noClass").addClass("yourClass");
But I would prefer an explicit statement about what removeClass()
returns. Because my second questions is: what is returned by removeClass and how is addClass can making use of it?
It returns the jQuery object. See the documentation of the removeClass function: http://api.jquery.com/removeClass/
And the jQuery object: http://api.jquery.com/Types/#jQuery
Excerpt from the documentation of the jQuery object:
A jQuery object contains a collection of Document Object Model (DOM)
elements that have been created from an HTML string or selected from a
document. Since jQuery methods often use CSS selectors to match
elements from a document, the set of elements in a jQuery object is
often called a set of "matched elements" or "selected elements".
It returns the elements you selected using the query:
$("[some query here]").removeClass("...").text("the text that must be set");
So, adding class1 and removing class2 can be done like bellow:
$("query .class2")
.removeClass("class2")
.addClass("class1");
On the documentation page you can see: Returns: jQuery.
Look at the documentation for removeClass, it tells you Returns: jQuery

Chaining selectors in jQuery

I'm a guy used to mootools' way of chaining selectors, and I can't seem to find anywhere how to do the same in jQuery.
Suppose I have a select element in the selectObj variable. What I need is to get the last option in that select.
In mootools I would have done something like:
var option = $(selectObj).getElement('nth-child(last)')
Can I do something similar, or what is the way of getting that last option in jQuery?
PS. I know about the parent > child selector, but I can't really use it because I don't know what selector has been used to get the select. I only have the resulting element.
$(selectObj).find(':last')
You can use find to perform another query within the current query.
In general, you can check out the Selectors and Traversal pages on jQuery docs when you're trying to figure out how to select something.
var option = $(selectObj).children(":last");
will return the last child of any element
You can also use .last() for this purpose.
jQuery has the :last Selector
$("tr:last").stuff()
Will do stuff to the last row in a table.

Categories