select by id in jquery - javascript

as all you know
$("#ID")
returns the element having ID.
but this code always return even there's no element.
alert($("#htrBuyerCouponNotice"));
alert(document.getElementById("htrBuyerConponNotice"));
in this case.
those two line results are diffrent.
I want to check whether there is an element has htrBuyerCouponNotice.
document.getElementByID return null if there's no element.

You can check the length property of the jQuery object to determine the number of matched elements, e.g.:
alert($(selector).length);
You can use it directly on if statements e.g.:
var $el = $(selector);
if ($el.length) { // only 0 will coerce to false
// ...
}
But most of the time you don't really need to know if the selector matched elements or not, because the jQuery built-in methods will be simply ignored, e.g.:
$('#nonExistent').hide();
The above statement will not cause any error even if the element was not found.
jQuery has also the size method, but I would recommend you to use the length property directly since it's publicly accessible, the size method is slightly slower since it is only a function that returns the value of length property.

because jQuery returns a list of selected elements, if there are no elements, you still get a return - its just a empty list.
check for $('#someID').length - should work if i remember corretly

When selecting elements, jQuery will always return an array of matching elements. In your case, $('#htrBuyerCouponNotice') is probably returning an empty array. Instead, check $('#htrBuyerCouponNotice').length.
Andrew

Try:
$("#htrBuyerCouponNotice").size()
It'll be zero if there's no nodes with that identifier, 1 if there is.

Related

$("#myElement").length vs. !!$("myElement") to check if the dom element exists?

I need to check if a certain dom element exists or not. I saw other posts which suggests length property to check that. That works fine. But It works even without length property. For example:
!!$("#myElement"); // true
!!$("#myElement").length; // true
Both the ways return same value. So is it ok to not use length property to check if the element exists?
No, always use length.
Your logic here is flawed as a jQuery object is never empty or null, it always returns an object even if no element is selected, hence you cannot reliably coerce it to a boolean to see if the selector matched any elements.
console.log(!!$('#exists')); // should be true
console.log(!!$('#doesNotExist')); // should be false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exists"></div>
As you can see above, both tests return true.

jQuery - .first() versus [0] element

Using jQuery 3.1.1, why are the results of these two different?
$('dd[data-something]').first().innerText;
^ returns undefined
$('dd[data-something]')[0].innerText;
^ returns valid data
Wouldn't the 0th element of an array also be the .first() element?
Edit: Thanks all, I got it, jQuery object versus DOM element. As the debugger clearly showed before I could delete this :) That's a clear sign its time to call it quits for the day.
Because first returns a jQuery object wrapped around the first raw DOM element in the set (which has no innerText property, but does have that handy text method), and [0] directly accesses that raw DOM element (which does have an innerText property on most browsers).
first() will return a jQuery object which is different from the normal JavaScript object and won't work with native JavaScript APIs, here's a qoute from the official documentation
the .first() method constructs a new jQuery object from the first element in that set.
The second one (index zero) will return a JavaScript object it's almost like calling the element using querySelectorAll()
So if you want to get the text use text() from jQuery and it will work
$('dd[data-something]').first().text('new text'); // this will change the text

Get the ID of an element where the class contains a given string

I am currently trying to figure out a way to get the ID of an element, depending on whether its class contains something. I'm not sure if there's a better way to do it than I currently am, but having looked around nothing fits exactly the need I have. The code I currently have is, where I am looking for a div element whose class contains the string "one" but is not limited to that. Currently there is only one element containing this string but the alert provides me with [Object NodeList] (I may well be overcomplicating this):
$idToMove = document.querySelectorAll('div[class^="one"]');
alert($idToMove);
document.querySelectorAll() Returns a node list (kind of like an array), if you are sure there will only ever be one you have a couple options.
1) Use .querySelector instead:
// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);
2) Access the first element in the returned list:
// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);
Make sure to null check returns of .querySelector and length check returns of .querySelectorAll.
Notice also, that I use ~= and not ^=. You can read on the MDN about the difference between all the equality operators. But for these two:
[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
[attr^=value]
Represents an element with an attribute name of attr and whose first value is prefixed by "value".
First get element from DOM and than from that element get id attribute:
1- If you need only first element then use querySelector like this:
let elms = document.querySelector('div[class~="one"]')[0].id
console.log(elms)
2- If you need all element those have this class then use querySelectorAll like this:
let elms = document.querySelectorAll('div[class~="one"]')
for(let i=0; i<elms.length; i++)
{
console.log(elms[i].id)
}
I think with "*" it works in more cases
document.querySelector('div[class*="words"]')
i tried it works absolutely amazing
window.frames[0].document.querySelector('td[id*="sss"]')

JavaScript HTML element to DOM selector

I have a function that requires a HTML element to perform the action on. I request the DOM selector as a parameter
function(document.body);
where element is the DOM query but somewhere else in the function I need the query as a string. Is it possible to turn the object into it's original string type? And if so, how?
You can do it the other way around. Pass your function a selector string:
functionName('body')
And then retrieve the relevant DOM element using .querySelector():
var el = document.querySelector(string);
The approach you are using is not going to produce the right results consistently in my opinion.
Passing in the element is going to mean that the element must be found beforehand and also is going to practically prevent finding other elements of similar location due to a lack of information.
Passing in a selector is an option, and then using that going forward if you need to find a similar set of elements but sometimes the selector is too complex to be placed in one string - for example if it needs filtering or some other metric.
Your best bet is to accept a callback function that returns the desired element or set of elements when you are dealing with complex selectors or locations for elements. It can simply return the same element each time if it is basic, or if it is more complicated the callback can access the DOM, filter based on some metric, and then return the subset which at times is ideal.
A callback function will provide the full amount of support without needing to always have a conversion to query string which is not always possible for complex structures.
If I understand you correct you could to this
function (elem) {
if (typeof elem === 'string' || elem instanceof String) {
elem = document.querySelector(elem);
}
var target = elem.querySelector(...);
}
To get the HTML string of an element use 'innerHTML'.
Temporary parent:
var div = document.createElement("div");
Append desired element to parent:
div.appendChild(document.body);
Test result:
alert(div.innerHTML);
If you are trying to get the string of the resulting element of 'querySelector()':
div.appendChild(document.body.querySelector('yourClass'));
The temporary parent ensures that you get the tags for the element returned. Otherwise you would only get the string for its child elements. If you want to use 'querySelectorAll()', just loop over the returned node array.

How do I find out whether an element with that ID exists or not?

I do a:
console.log($('#test'));
I know that test doesn't exist. If I do a console.log, it doesn't output undefined/null. Rather it ouputs something like an empty array and when I check that array it looks like it returns the jQuery object itself.
I also tried:
if ($('#test')){
//do something
}
But it still doesn't work. I want to know whether the ID I am selecting exists on page or not. How do I do that using jQuery?
It's something like 20x faster to do this:
if (document.getElementById("test"))
compared to the jQuery operation to just determine if a DOM object with that id exists in the page. jQuery can do a lot for you, but when its general selector engine and general object structure isn't needed, it's not the quickest way to do things.
As others have said, $("#test") is always a valid jQuery object, even if #testdoesn't exist. If the #test object doesn't exist, then $("#test") will be a jQuery object that has no DOM objects in it (the internal array will have a .length === 0), but it's still a valid object.
In JavaScript, objects are always truthy, so using it in that fashion will always pass the condition.
You need to check the length property. A response of 0 is falsy, and will work as expected.
if ($('#test').length) {
// ...
}
This is unlike document.getElementById(), which returns null if the element with that id attribute does not exist.
If this is confusing, you could always write a quick jQuery plugin.
$.fn.exists = function() {
return !!this.length;
};
You can then call exists() on a jQuery collection, to ensure that selector has matched at least one item.
Use '(' and ')' for 'if' statements, and check if the returned array has length greater than 0:
if ($('#test').length > 0){
//do something
}
use something like this
if ($('#test').length > 0){
alert('hi')
}else
{
alert('hello')
}
Live Demo ​
Use
if ($('#test').length > 0){
//do something
}
the length tells you how many items were selected if it is 0 no element has the id test.
best way for this is to check length of the selected element
if ($('#test').length > 0){
//do something
}
But if you want to create a exist function jQuery welcomes you just add the line in your script
jQuery.fn.exists = function(){return this.length>0;}
and now you can Check if element exist or not
if ($(selector).exists()) {
// Do something
}
console.log($('#test'));
This won't print the value because it represents the object found in the DOM with the id test.
If you want to get values, use $("#test").val(); or $("#test").html();
If you want to check existence, do the length test as suggested above.
Also, if you're testing for the existence of a generated element (something you added to the DOM), make sure you checkout .live (http://api.jquery.com/live/). This is need for all elements that are created after the page is loaded.

Categories

Resources