Jquery selector performance & behavior [duplicate] - javascript

This question already has answers here:
Performance of jQuery selectors vs local variables
(5 answers)
Closed 7 years ago.
I have a strange question about jquery selector behavior.
First approach:
$('#div').find('#something').html('hahah');
$('#div').find('#something').html('hahah');
$('#div').show();
Second approach:
var $div = $('#div');
$div.find('#something').html('hahah');
$div.find('#something').html('hahah');
$div.show();
I know that it might not have too much difference, but is the second faster than the first?? I've always used the second approach but I'm not sure if there is a difference because I don't know how the jquery selector algorithm works.

The second way is faster/better because you have cached the selector.
Everytime you call $('selector'), the jQuery selector engine(sizzle) is called to locate your desired elements.
However, when you store them in a variable, you do not need to repeatedly call the selector engine as the results are stored.
Note, in your example above, caching can be further improved by storing the find() result as well
var $something = $('#div').find('#something');
$something.html('hahah');
$something.html('hahah');
$something.show();

Related

JQuery not initializing variable [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 years ago.
I have the following piece of code in my javascript file(helper.js):
var a = $('li')
$(window).keydown(function(e) {
\\whatever
})
it is supposed to select all tags in my html file and store in in a, however when I use this code, it a is null(which it shouldn't be). when I change my code to:
$(window).keydown(function(e) {
var a = $('li')
\\whatever
})
a is initialized correctly. Does anyone knows why? I am using jquery 3.3.1.
If you are dealing with the DOM (Document Object Model), use $(document).
If you are dealing with how user interact with the window, screen and so on, use $(window)
Here is a link for better understanding window and document
Window vs Dom

DOM equivalent of jQuery .clone() function [duplicate]

This question already has an answer here:
How to duplicate a div in JavaScript
(1 answer)
Closed 5 years ago.
What is a good equivalent for the jQuery .clone() function in regular DOM JavaScript? I performed multiple searches (on both SO and Bing) and didn't find a specific answer. I need to produce a copy of an element and all of its internal elements. The clone must have all of the elements and content of the source elements. If possible, make the solution as compact or efficient as possible.
try this
var clonedElement = document.getElementById('id').cloneNode(true)
var element= document.getElementById("myid");
var clone= element.cloneNode(true);

single addEventListener with Multiple selects [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 5 years ago.
I have looked around and I haven't really been able to find anything that solves my problem. There is a post using buttons but I can't seem to modify it for my needs.
I am trying to use only one event listener for multiple selects. I'd like to return the id of the select, and the value selected but as far as I can figure I either need to use document.getElementById("ID").addEventListener('change',func(),true) for each id or document.getElementsByTagName('select').addEventListener('change', func(), true) and I get an error that says:
selection.addEventListener is not a function. (In 'selection.addEventListener('change', func(), true)', 'selection.addEventListener' is undefined)
I was hoping someone could take a moment and show me where I am going wrong or if I need to use a different method to accomplish my task.
thanks for the help
The method getElementsByTagName returns HTMLCollection of elements, and not a DOM Element, so you can't use addEventListener on that.
What you can do is go over all the elements in the HTMLCollection and add the event you want to them:
let selectElements = document.getElementsByTagName('select');
Array.prototype.forEach.call(selectElements, function(el) {
eladdEventListener('change', func(), true)
})

Why can I not find using data attribute [duplicate]

This question already has answers here:
jQuery Data vs Attr?
(3 answers)
Closed 5 years ago.
In code I do this:
var markerName = $(fileInput).closest('tr.file-input-row').find('input[type="text"]')[0].value.replace(/[^a-z0-9]/gi, '-');
$.data(fileInput, 'for', markerName);
in this case, markerName is "file-1"
If I check using:
$('input[type="file"][data-for="file-1"]')
I get an object with length equal to 0... so not found.
However, if I do:
$('input[type="file"]:first').data().for
in this case, the first input[type="file"] is the same input I set the data attribute for, I get:
"file-1"
...as expected.
It looks like it is being set, but it is then not accessible.
Any thoughts why?
TIA
This is not working because you aren't updating the DOM object when you perform the data-for adjustment in the first part of your code. To update the DOM object you should use attr(key, value).
For more info on the differences between data and attr there is a good answer related to this: jQuery Data vs Attr?
If I check using:
$('input[type="file"][data-for="file-1"]')
Neither .data() nor jQuery.data() is part of the object returned by jQuery() : $() call.

Is there a += available for attr() and val()? [duplicate]

This question already has answers here:
Is it possible to do ".value +=" in JQuery?
(5 answers)
Closed 8 years ago.
Since I've moved to jQuery development has sped up for a great deal, but there is one thing which has become a little more time-consuming: appending some string to an attribute/value.
For example, if you wanted to append a letter to the value of a textbox, you would normally do:
input.value += 'a';
but now using jQuery, it has become:
input.val(input.val() + 'a');
I know it wouldn't be too hard to create a function which can do this and then append that function to jQuery.fn, but I was rather wondering whether there is such a function perhaps already available. I haven't found any so far. Or is there perhaps a better technique of appending a string to a value/attribute than what I'm doing at the moment?
If you know that your element has a value attribute, there is no reason not to use
input.value += 'a';
There is nothing to stop you using plain JavaScript in your jQuery scripts.
In fact,
input.val(input.val() + 'a');
has no benefits over using plain 'js', except if your input is a jQuery object and you want to chain methods.
I'd suggest overall
var $input = $('#someInput');
$input[0].value += 'a'; //get the DOM object from your jQuery object

Categories

Resources