I don't want the else part in tertiary operator [duplicate] - javascript

This question already has answers here:
Ternary operators in JavaScript without an "else"
(13 answers)
Closed 1 year ago.
function clear_error(id){
(document.getElementById(id) != undefined) ? (document.getElementById(id).innerHTML = "") : console.log('span is not created yet');
}
I have to check that a span element has been created/defined for my error or not, if it is created then remove the inner text for the new error if not then do nothing, as i have made an error function of it in the specified class.

A ternary isn't the best tool here. Typically the conditional operator (? :) is used when you want to evaluate a condition and obtain a new value based on whether the condition is true/false. You can could && to short-circuit:
function clear_error(id) {
const elem = document.getElementById(id); // store the element to avoid re-querying the DOM
elem && elem.innerHTML = "";
}
but that to me doesn't read very well, so a standard if-statement would work better in my opinion:
function clear_error(id){
const elem = document.getElementById(id); // store the element to avoid re-querying the DOM
if(elem) {
elem.innerHTML = "";
}
}

Just use null :
(document.getElementById('jj') != undefined) ? (document.getElementById(id).innerHTML = "") : null

Related

How to check empty in variable in Google Apps Script [duplicate]

This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Google Spreadheets Scripts: check if cell is empty
(3 answers)
Closed 1 year ago.
I have a variable that can be either empty, number or text. I like to find only empty one. But the following codes using .length returned null for 0 number, though it returned 1 for "0" string . .toString.length even didn't work. Any suggestion? Thank you!
function test() {
// criteria can be either empty, number or text. How can I check whether the critieria is empty?
// In the example below, critiera_2.length returned null, not 1.
criteria_1 = "";
Logger.log(criteria_1.length);
criteria_2 = 0;
Logger.log(criteria_2.length);
criteria_3 = "0";
Logger.log(criteria_3.length);
criteria_4 = "X";
Logger.log(criteria_4.length);
criteria_1 = "";
Logger.log(criteria_1.toString.length);
criteria_2 = 0;
Logger.log(criteria_2.toString.length);
criteria_3 = "0";
Logger.log(criteria_3.toString.length);
criteria_4 = "X";
Logger.log(criteria_4.toString.length);
}
criteria_1 = "";
console.log(criteria_1.toString() == ''); // output: true
const test = x => console.log(x.toString()==='');
test(""); // true
test(0); // false
test("0"); // false
test("X"); // false
It's turned out that you don't even need toString() it could be just x===''
To check for an empty string, a simple approach would be to use === operator
if (criteria_1 === "") {
//...
}

Json returns as undefined, replace undefined with text [duplicate]

This question already has answers here:
Javascript: use either a variable, or if it's undefined, a default string
(7 answers)
Closed 4 years ago.
first time dealing with json, so not really sure..
when a user online the api returns with
user example
live true
viewers 22
passwordProtected false
banned false
but when im offline "viewers" gets removed.
so data.viewers comes back as undefined, how can i change it to e.g offline?
script:
<script>
$.getJSON('https://example.com/api/example', function(data) {
var text = `${data.viewers}`
$(".mypanel").html(text);
});
</script>
You can use the hasOwnProperty function.
var text = "offline";
if(data.hasOwnProperty('viewers'){
text = data.viewers;
}
You could check for undefined like so:
var text = "offline";
if (data.length && data.viewers !== undefined) {
var text = data.viewers;
}
or with a ternary operator:
var text = (data.viewers !== undefined) ? data.viewers : "offline";
Ps. no need for the interpolation when saving a variable. ie `${data.viewers}`
This is used when adding variables to a string value like html.

Check if elements are part of wrapper [duplicate]

How can I check if one DOM element is a child of another DOM element? Are there any built in methods for this? For example, something like:
if (element1.hasDescendant(element2))
or
if (element2.hasParent(element1))
If not then any ideas how to do this? It also needs to be cross browser. I should also mention that the child could be nested many levels below the parent.
You should use Node.contains, since it's now standard and available in all browsers.
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
Update: There's now a native way to achieve this. Node.contains(). Mentioned in comment and below answers as well.
Old answer:
Using the parentNode property should work. It's also pretty safe from a cross-browser standpoint. If the relationship is known to be one level deep, you could check it simply:
if (element2.parentNode == element1) { ... }
If the the child can be nested arbitrarily deep inside the parent, you could use a function similar to the following to test for the relationship:
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
I just had to share 'mine'.
Although conceptually the same as Asaph's answer (benefiting from the same cross-browser compatibility, even IE6), it is a lot smaller and comes in handy when size is at a premium and/or when it is not needed so often.
function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
while((c=c.parentNode)&&c!==p);
return !!c;
}
..or as one-liner (just 64 chars!):
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
and jsfiddle here.
Usage:
childOf(child, parent) returns boolean true|false.
Explanation:
while evaluates as long as the while-condition evaluates to true.
The && (AND) operator returns this boolean true/false after evaluating the left-hand side and the right-hand side, but only if the left-hand side was true (left-hand && right-hand).
The left-hand side (of &&) is: (c=c.parentNode).
This will first assign the parentNode of c to c and then the AND operator will evaluate the resulting c as a boolean.
Since parentNode returns null if there is no parent left and null is converted to false, the while-loop will correctly stop when there are no more parents.
The right-hand side (of &&) is: c!==p.
The !== comparison operator is 'not exactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true, but if the child's parent is the parent then it evaluates to false.
So if c!==p evaluates to false, then the && operator returns false as the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ; semicolon is required.)
So when the while-loop ends, c is either a node (not null) when it found a parent OR it is null (when the loop ran through to the end without finding a match).
Thus we simply return that fact (converted as boolean value, instead of the node) with: return !!c;: the ! (NOT operator) inverts a boolean value (true becomes false and vice-versa).
!c converts c (node or null) to a boolean before it can invert that value. So adding a second ! (!!c) converts this false back to true (which is why a double !! is often used to 'convert anything to boolean').
Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one could even omit the function (wrapping) and just use the while-loop:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
c=a; while((c=c.parentNode)&&c!==b); //c=!!c;
if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
//do stuff
}
instead of:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
c=childOf(a, b);
if(c){
//do stuff
}
Another solution that wasn't mentioned:
Example Here
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it's a child
}
It doesn't matter whether the element is a direct child, it will work at any depth.
Alternatively, using the .contains() method:
Example Here
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it's a child
}
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
Take a look at Node#compareDocumentPosition.
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_PRECEDING, and DOCUMENT_POSITION_FOLLOWING.
Not supported in IE<=8.
I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains element method. Hope this will help others as well.
Below is the function:
function isChildOf(childObject, containerObject) {
var returnValue = false;
var currentObject;
if (typeof containerObject === 'string') {
containerObject = document.getElementById(containerObject);
}
if (typeof childObject === 'string') {
childObject = document.getElementById(childObject);
}
currentObject = childObject.parentNode;
while (currentObject !== undefined) {
if (currentObject === document.body) {
break;
}
if (currentObject.id == containerObject.id) {
returnValue = true;
break;
}
// Move up the hierarchy
currentObject = currentObject.parentNode;
}
return returnValue;
}
Consider using closest('.selector')
It returns null if neither element nor any of its ancestors matches the selector. Alternatively returns the element which was found
try this one:
x = document.getElementById("td35");
if (x.childElementCount > 0) {
x = document.getElementById("LastRow");
x.style.display = "block";
}
else {
x = document.getElementById("LastRow");
x.style.display = "none";
}
TL;DR: a library
I advise using something like dom-helpers, written by the react team as a regular JS lib.
In their contains implementation you will see a Node#contains based implementation with a Node#compareDocumentPosition fallback.
Support for very old browsers e.g. IE <9 would not be given, which I find acceptable.
This answer incorporates the above ones, however I would advise against looping yourself.

Append class with if statement

I just created a variable for a specific site of mine but I want to append a class entitled "partner-text" if I'm actually on that site. If I'm on a different site then don't append it. How can I do that?
use(function() {
var inPartnerPath = currentPage.getPath().indexOf("partners_Skate_Daily");
// to check if the site is under partners_Skate_Daily folder if yes then it should return true
var isPartner = (inPartnerPath != -1) ? 'true' : 'false';
return {
isPartner: isPartner
};
});
'true' and 'false' are strings. You want to use the boolean values true/false.
You don't even need the ?: here, != already returns you a boolean.
var isPartner = inPartnerPath != -1;

Trouble setting JavaScript variable of object using ternary operator

Hi Guys I’m having trouble trying to set a variable (val) to be one of 2 possible object attributes. The below code explains what I’m trying to do.
function myFnct(elem, imgSrcType) {
var val = imgSrcType == "bg" ? elem.style.backgroundImage : elem.src;
val = 'image.jpg'
}
I’m using a ternary operator to try and avoid having to write:
if (imgSrcType === "bg") {
elem.style.backgroundImage = "url('image.jpg')";
}
else {
elem.src = "image.jpg";
}
Basically the ‘val’ variable is not getting set correctly as I guess its something to do with elem object. I’m trying to avoid using the if statement as I will need to use it a few times within the function. And I’m trying to keep is as DRY as possible.
Any help getting it to work with the ternary operator method would be awesome!
if (imgSrcType === "bg") {
elem.style.backgroundImage = "url('image.jpg')";
}
else {
elem.src = "image.jpg";
}
ugly but working rewrite:
void (
imgSrcType === 'bg'
&& (elem.style.backgroundImage = "url('image.jpg')")
|| (elem.src = "image.jpg")
);
Equals:
void (
imgSrcType === 'bg'
? (elem.style.backgroundImage = "url('image.jpg')")
: (elem.src = "image.jpg")
);
So by adding parentheses (elem.src = "image.jpg") you can do the assignment. You can also use a comma to return something in a value assignment.
Using this knowledge, you could rewrite myFnct:
function myFnct(elem, imgSrcType) {
var val = (
void( imgSrcType == "bg"
? (elem.style.backgroundImage = "url('image.jpg')")
: (elem.src = "image.jpg") ), //<= ternary done - comma
'image.jpg'
);
//now val = 'image.jpg'
}
Note: this is all about what is possible. If you need/want to keep your code readable, using the if ... else statement is the better option.
Ternary operations can only assign their outcome to a single variable. They are useful if you are setting that single variable to different values depending on the result of a boolean expression. Since you are trying to assign the image URL to either the background-image or to the source, you cannot use a simple ternary operation. The other answers are using pretty complex/quasi-obfuscated code to accomplish what could be done with a simple if/else statement. Your code - especially for such a simple operation - should be easy to read. So, I recommend just sticking with the following:
function setImage(elem, imgSrcType)
{
var imgURL = "image.jpg";
if(imgSrcType == "bg")
{
elem.style.backgroundImage = "url('" + imgURL + "')";
}
else
{
elem.src = imgURL;
}
}

Categories

Resources