Applying variable to element jquery - html

I'm wondering if you can do this in jquery. I'm using version 1.10:
var myImage = $('#myImage');
What i basically want to do is assign the image as a variable so that i can use it anywhere. I want to use it during event handling:
E.g.
myImage.click(function () {
alert('Image Clicked');
});
If the above code is incorrect, I would really like to know the appropriate code.

Yes you can do it. In fact, it is recommended that you assign it to a variable so that you selector is not evaluated each time you use it. It is good for performance reasons.
Finding element by Id (such as in your case $('#myImage');) is fast but imagine if you have a selector like
$('ul > li.myClass:has(p) a:eq(2)')
Using a variable will speed things up for you in such scenarios.
I usually use $ sign in variable name like. var $varName = $('.selector') It helps me better understand the code and to distinguish between regular variables and variables that contain DOM elements.

Related

jQuery - Strings and targeting

I've tried to google my question but it makes me even more confused. My question is:
Here's the jQuery code:
$(document).ready(function() {
$(window).resize(function() {
if ($(this).width() < 200) {
$("p").css("color", "red");
} else {
$("p").css("color", "green");
}
});
}
Why do we write (this) and not ("this") ?
How do I know if (document) and (window) should be written with " " - and why's that?
Maybe you could link me somewhere that explains my issue. My code apparently works either way, I'm just curious about the why.
In JavaScript namespace, this is reserved [source].
The JavaScript object literal this refers to the inherited object from the present state in the current execution.
Another example of this we can see is when we are looping through an array and the object this would symbolize the current array object. You may, for example, see this.title, or this.description if we were iterating through a database array of blog posts.
this in jQuery refers to the inherited object. When we add the quotation marks, and it becomes a string, such as "this". This makes jQuery parse it as a DOM selector.
Then we are now looking for the HTML DOM selector <this>, which to my knowledge, does not actually exist in the accepted HTML syntax standards.
As otherwise stated, the concept of this will become tricky when you are working in other JavaScript environments, such as React or Angular. Within the context of a functional component, this becomes the state, such as handling user sessions.

Display value + text using jQuery

I am a total beginner. I have a form in HTML and am trying to calculate a specific value using jQuery. I want this value to be displayed in paragraph <p id="final"></p> under the submit button, but am actually not sure, why my code isn't working.
jQuery(document).on("ready", function() {
jQuery("final").hide();
jQuery("#form").submit(function(e){
e.preventDefault();
const data = jQuery(this).serializeArray();
/*
some calculations
*/
$('#final').html($('#final').html().replace('','result + " text"'));
jQuery("#final").show();
}
}
Do you have any idea, what could I be doing wrong??
You've got a several issues here.
Firstly, don't mix jQuery and $. If you're using the former, it's normally to avoid jQuery's alias, $, from conflicting with other code that might use $.
Secondly, you don't actually do any calculation (from what I can see in your code), so I'm not sure what you're wanting to output. I'll assume you're going to fill that in later.
Thirdly, jQuery('final').hide() is missing the # denoting you're targeting by element ID.
Fourthly, the line
$('#final').html($('#final').html().replace('','result + " text"'));
...doesn't quite do what you think it does. For one thing, it makes no reference to your data variable. And running replace() on an empty string doesn't make much sense.
All in all I'm guessing you want something like (note also how I cache the #final element - that's better for perforamnce):
jQuery(function() { //<-- another way to write a document-ready handler
let el = jQuery('#final');
el.hide();
jQuery("#form").submit(function(e){
e.preventDefault();
const data = jQuery(this).serializeArray();
let calc = 5+2; //<-- do what you need to here
el.html(calc).show();
}
}
Guessing result is your variable and your above code is your current status, you should fix the html replacement to something like (depending on your acutal usecase):
$('#final').html(result + " text"));

Parent node in react-testing-library

The component that I have testing renders something this:
<div>Text<span>span text</span></div>
As it turns out for testing the only reliable text that I have is the 'span text' but I want to get the 'Text' part of the <div>. Using Jest and react-testing-library I can
await screen.findByText(spanText)
This returns an HTMLElement but it seems limited as I don't have any of the context around the element. For example HTML methods like parentNode and previousSibling return null or undefined. Ideally I would like to get the text content of the parent <div>. Any idea how I can do this with either Jest or react-testing-library?
A good solution for this is the closest function.
In description of closest function is written: Returns the first (starting at element) including ancestor that matches selectors, and null otherwise.
The solution would look like this:
screen.getByText("span text").closest("div")
Admittedly, Testing Library doesn't communicate clearly how to do this. It includes an eslint rule no-direct-node-access that says "Avoid direct Node access. Prefer using the methods from Testing Library". This gives the impression that TL exposes a method for a situation like this, but at the moment it does not.
It could be you don't want to use .closest(), either because your project enforces that eslint rule, or because it is not always a reliable selector. I've found two alternative ways to tackle a situation like you describe.
within():
If your element is inside another element that is selectable by a Testing Library method (like a footer or an element with unique text), you can use within() like:
within(screen.getByRole('footer')).getByText('Text');
find() within the element with a custom function:
screen.getAllByText('Text').find(div => div.innerHTML.includes('span text'));
Doesn't look the prettiest, but you can pass any JS function you want so it's very flexible and controllable.
Ps. if you use my second option depending on your TypeScript config you may need to make an undefined check before asserting on the element with Testing Library's expect(...).toBeDefined().
But I have used HTML methods a lot and there was no problem yet. What was your problem with HTML methods?
You can try this code.
const spanElement = screen.getElementByText('span text');
const parentDiv = spanElement.parentElement as HTMLElement;
within(parentDiv).getElementByText('...');

Any difference between .innerHTML and .set('html','') in mootools?

To set the html of elements on my site, I use mostly
$('elementId').innerHTML = "<p>text</p>";
Looking through the mootools docs, I found this example given:
$('myElement').set('html', '<div></div><p></p>');
Is there any difference between these? Should I go through and change .innerHTML to the mootools method, or doesn't it make a difference?
the reason why the first one works is because - as it stands - a $ selector (document.id) in mootools returns the actual element. this - in normal browsers - is identical to document.getElementById() and the element object exposes any and all of its attributes/properties for you to edit.
the problems with NOT using .set are:
when mootools 2.0 aka MILK gets released, it won't work as it will be wrapped like jQuery and the selector won't return the object (mootools is becoming AMD hence it won't modify native Types - Element, Array, Number, String, Function(maybe!) - prototypes).
you cannot chain this. with set you can: $('someid').set("html", "loading...").highlight();, for example.
set is overloaded - it can set either a single property or multiples by means of passing an object. eg, element.set({html: "hello", href: "#", events: boundObj});
look at https://github.com/mootools/mootools-core/blob/master/Source/Element/Element.js#L936-942 - you can pass an array as an argument and it will join it for you, this makes it easy to work with multi-line strings and ensures performance in IE
edit: the BBT fan has kind of opened a separate topic: should the framework try to block you / prevent you from doing things that break the browser?
if you want to, you can add disallowed elements by changing that setter Element.Properties.html.set = function() { var tag = this.get("tag"); ... check tag }; - isn't mootools great?
mootools - by default - will NOT try to prevent you from doing stupid shit [tm] - that's your responsibility :) try setting height on an element to a negative value in IE, for example. should the Fx class prevent you from doing that? No. Should the setter prevent you? No. The footprint of constant checks to see if you are not breaking means it will slow everything down in performance-critical cases like animations.

How does jQuery work when there are multiple elements with the same ID value?

I fetch data from Google's AdWords website which has multiple elements with the same id.
Could you please explain why the following 3 queries doesn't result with the same answer (2)?
Live Demo
HTML:
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS:
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a type selector, like this:
$('span[id="a"]');
The reason for this is because a type selector is much more efficient than an attribute selector. If you qualify your attribute selector with a type selector, jQuery will first use the type selector to find the elements of that type, and then only run the attribute selector on those elements. This is simply much more efficient.
There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.
How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.
Use classes if you want multiple objects to have the same identifier.
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.
You could do so like this:
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
Or, using jQuery:
$("div *").filter(function() {return(this.id == "a");});
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a and if so, just used document.getElementById("a"). If the selector is more complex than that and querySelectorAll() exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll() does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll() implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.
jQuery's id selector only returns one result. The descendant and multiple selectors in the second and third statements are designed to select multiple elements. It's similar to:
Statement 1
var length = document.getElementById('a').length;
...Yields one result.
Statement 2
var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
if (document.body.childNodes.item(i).id == 'a') {
length++;
}
}
...Yields two results.
Statement 3
var length = document.getElementById('a').length + document.getElementsByTagName('div').length;
...Also yields two results.
What we do to get the elements we need when we have a stupid page that has more than one element with same ID? If we use '#duplicatedId' we get the first element only. To achieve selecting the other elements you can do something like this:
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId.
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html> and <body> tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.
<div>
<span id="a" class="demo">1</span>
<span id="a" class="demo">2</span>
<span>3</span>
</div>
JQ:
$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");
Access individual item
<div id='a' data-options='{"url","www.google.com"}'>Google</div>
<div id='a' data-options='{"url","www.facebook.com"}'>Facebook</div>
<div id='a' data-options='{"url","www.twitter.com"}'>Twitter</div>
$( "div[id='a']" ).on('click', function() {
$(location).attr('href', $(this).data('options').url);
});
you can simply write $('span#a').length to get the length.
Here is the Solution for your code:
console.log($('span#a').length);
try JSfiddle:
https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/