How to find if element with specific id exists or not - javascript

In my JavaScript I want to check whether the element with specific id is exist or not, I tried it with 2 ways
1).
var myEle = document.getElementById("myElement");
if(myEle == null){
var myEleValue= document.getElementById("myElement").value;
}
2).
if(getElementById("myElement")){
var myEleValue= document.getElementById("myElement").value;
}
but it gives same error as below -
Object expected

var myEle = document.getElementById("myElement");
if(myEle) {
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value

You can simply use if(yourElement)
var a = document.getElementById("elemA");
var b = document.getElementById("elemB");
if(a)
console.log("elemA exists");
else
console.log("elemA does not exist");
if(b)
console.log("elemB exists");
else
console.log("elemB does not exist");
<div id="elemA"></div>

getElementById
Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists
see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Truthy vs Falsy
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
When the dom element is not found in the document it will return null. null is a Falsy and can be used as boolean expression in the if statement.
var myElement = document.getElementById("myElement");
if(myElement){
// Element exists
}

You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}

document.getElementById('yourId')
is the correct way.
the document refers the HTML document that is loaded in the DOM.
and it searches the id using the function getElementById()
which takes a parameter of the id of an element
Solution will be :
var elem = (document.getElementById('myElement'))? document.getElementById('myElement').value : '';
/* this will assign a value or give you and empty string */

Use typeof for elements checks.
if(typeof(element) === 'undefined')
{
// then field does not exist
}

if( document.getElementById("myElement") ){
console.log('exists');
}
or shorter way
if( document.querySelector("#myElement") ){}

this works for me to check if element exits
let element = document.getElementById("element_id");
if (typeof(element) !== 'undefined' && element!== null)
{
//content
}

Related

How to add field to Object that may not yet exist?

I have a this._champ object (which is undefined by default).
I browser an array, and want to add this field with a value : this._champ[champ.name][ele.infos[0].StackableRangeName] = ele.value; but at the first iteration, [champ.name] is undefined, and [ele.infos[0].StackableRangeName] is always undefined, how to manage this?
I tried this ternary operator but it isn't working:
this.champ[champ.name] != undefined ? this._champ[champ.name].push({ele.infos[0].StackableRangeName: ele.value}) : this._champ.push({champ.name: {ele.infos[0].StackableRangeName: ele.value}})
This is a common idiom for initializing something with a default value if it's not yet set:
this.champ[champ.name] = this.champ[champ.name] || []
Just check for existence of the key. and then push value:
if(this.champ && !this.champ.hasOwnProperty(champ.name)) {
this.champ[champ.name] = [];
}
this._champ[champ.name].push({ele.infos[0].StackableRangeName: ele.value});

javascript check object exists

I have following code to check the object whether exists for item listing.
For testing purpose, i only have one object sub_total_0, however the script keep looping because typeof cannot determine sub_total_1 is undefined or not exists, and keep going 2,3,4,5,...
var i = 0;
while (typeof document.getElementById("sub_total_" + i) != "undefined") {
var obj_sub_total = document.getElementById("sub_total_" + i);
if (obj_sub_total != "undefined") {
if (fr.order_method_id.value == 1) {
obj_sub_total.style.visibility = "visible";
} else {
obj_sub_total.style.visibility = "hidden";
}
}
i++;
}
You have
typeof document.getElementById("sub_total_" + i) != "undefined"
and
if (obj_sub_total != "undefined") {
getElementById returns either null or an HTML element. Neither of these are the string "undefined" and the type of each of this will be "object". Thus your conditions don't make sense.
You test for truthfulness instead. An HTML element will always be true and null will always be false.
while (document.getElementById("sub_total_" + i)) {
and
if (obj_sub_total) {
Your check doesn't work because using typeof on getElementById's return value will always give you "object", because it returns null if it can't find it, and typeof null is "object".
Just check the return value directly: If there's an element, it's a "truthy" value (one that coerces to true when used as a condition); if there isn't one, null is a "falsey" value (coerces to false).
So:
while (document.getElementById("sub_total_" + i)) {
You also don't need to look it up twice, which is what you're currently doing; instead:
var obj_sub_total;
while ((obj_sub_total = document.getElementById("sub_total_" + i)) != null) {
(You don't technically need the != null there, but without it it looks a bit like you've accidentally used = where you wanted ==.)
Another alternative would be to use a class and querySelectorAll:
var list = document.querySelectorAll(".sub_total");
Then loop while i is < list.length, e.g.:
var list = document.querySelectorAll(".sub_total");
for (i = 0; i < list.length; ++i) {
var obj_sub_total = list[i];
// ...
}
Or you could do that even when using ids:
var list = document.querySelectorAll("[id^=sub_total]");
getElementById() return null if element is not found, and the type of null is object that is why your condition is not working.
You can just check whether it is a truthy value and since the while() loop validates the object there is no need for the if condition
var i = 0,
obj_sub_total;
while (obj_sub_total = document.getElementById("sub_total_" + i)) {
console.log(obj_sub_total)
if (fr.order_method_id.value == 1) {
obj_sub_total.style.visibility = "visble";
} else {
obj_sub_total.style.visibility = "hidden";
}
i++;
}
Demo: Fiddle

How to check if string is present in variable in jquery

I have the variable like
var myVar = "The man is running"
pattern = "run"
I want to check via jquery that if it conatins words "run"
Like
if($(myVar).(:contains(pattern)))
return true
Is this possible
RegExp option...just because..RegExp.
var pattern = /run/;
//returns true or false...
var exists = pattern.test(myVar);
if (exists) {
//true statement, do whatever
} else {
//false statement..do whatever
}
You would use the Javascript method .indexOf() to do this. If you're trying to test whether the text of a DOM element contains the pattern, you would use this:
if($(myVar).text().indexOf(pattern) != -1)
return true;
If the variable myVar isn't a selector string, you shouldn't wrap it in the jQuery function, though. Instead, you would use this:
if(myVar.indexOf(pattern) != -1)
return true;
You do not need jQuery for this. Just check for the index of the string.
if (myVar.indexOf(pattern) !== -1) { ... }
Regex?
var hasRun = /run/i.test(myVar) // case insensitive

Checking if a parameter is assigned or not in javascript

I have a function with 2 parameters, it should work whether a the 2nd parameter is assigned or not in the bracket. Basically, if it's assigned then do something if not do something else or just don't bother about it.
vf.showHide = function (trigger, target) {
var $trigger = $(trigger),
trigParent = $trigger.parent(),
trigDataView = $trigger.data('view'),
numShown = $trigger.data('showalways'),
basketSubtotalElem = $('.subtotal .monthlyCost span.price, .subtotal .oneOffCost span.price, .subtotal label h3, .vat *');
target = target || null; // This is the 2nd parameter but I don't know if this right...
trigParent.delegate(trigger, 'click', function (e) {
var elem = $(this);
target = $(elem.attr('href'));
e.preventDefault();
if (trigDataView === 'showhide') {
if($('.filterBlock')){
if (target.is(':visible')) {
target.hide();
elem.find('span').removeClass('minus').addClass('plus');
} else {
target.show();
elem.find('span').removeClass('plus').addClass('minus');
}
}
}
});
}
So if the function is called like this: vf.showHide('a', 'div') it works and if it's called with 1 parameter like this: vf.showHide('a') it's should still works and error is thrown.
Many thanks
When you invoke a function, if you pass fewer parameters than expected, the parameters you omit are given the undefined value. So in your case:
vf.showHide = function(trigger, target) {
if (target === undefined) {
//target parameter is not passed any value or passed undefined value
//add code to process here, e.g. assign target a default value
}
}
target = target || null: if target is evaluated to false, it's assigned to null. Take notice that empty string, zero number (0), NaN, undefined, null, false are evaluated to false. So please be careful to write code like that.
target = target || null will work.
What you are doing here is declare an local variable within the function's scope.
Within each function, a local variable corresponding to the the name of the parameters are created to hold the passed in value.
If the parameters are not passed in, it will remain as 'undefined' local variable.
function (a, b) {
//a, b are declared.
}
what target = target || null does is just assign a value to an declared local variable it use the || expression:
The value of of || expression is determined by the first operands return true.
true || 2 will be valued as true
false || 2 will be valued as 2

what happens to a javascript variable assign with a non existent variable

I'm assigning a javascript variable with a value as
var newline = $("#newline").val();
The $("#newline").val() may or may not exist (in some cases, the #newline may not exist in the DOM, or even if it exists, it may not have any value).
I want to check whether the var newline is set or not. How do I do that?
This comes down to "What does the jQuery val method return if there are no elements matching the selector in the DOM?"
The answer to that is undefined so:
if ( typeof newline === "undefined" ) {
}
jQuery:
(function() {
if (this && this[0] && this[0].value) {
// Has a value
} else {
// Has no value
}
}).call($("#newline"));
this[0] is the HTML Element itself, rather than a jQuery Object.
Pure JavaScript:
(function() {
if (this && this.value) {
// Has a value
} else {
// Has no value
}
}).call(document.getElementById("newline"));

Categories