Currently, my javascript is creating pages dynamically, so when the user clicks X, the new html code is generated for that option, if B then vice versa.
Although, I'm getting "undefined" errors. Even though I do check for the variables before they're passed into the function.
My current non-working prototype looks like this
var appName;
if(evt.target.getAttribute("appName") != "" || evt.target.getAttribute("appName") != null){
appName = evt.target.getAttribute("appName");
}
Before that, I've tried using something which looks like this
var appName = evt.target.get("appName");
if (typeof appName != typeof undefined && appName !== false) {
appName = evt.target.getAttribute("appName");
}
else appName = 'boo';
That still returns undefined.
Lastly, I tried more or less the same approach but it still returns
Uncaught TypeError: Cannot read property 'getAttribute' of undefined
The code for the following looks like that :
var appName = '';
if(evt.target.hasAttribute("appName")){
appName = evt.target.getAttribute("appName");
}
else appName = 'boo';
How would I check if the attribute is actually set and I can proceed if not then I would like to pick alternate course for the code.
Thanks for your help and time spent.
evt.target is undefined, which means that you need to check for that before trying getAttribute(). This is one of the options you have, mostly depending on what your "alternate course for the code" is:
var appName;
if(evt && evt.target && ( evt.target.getAttribute("appName") != "" || evt.target.getAttribute("appName") != null )){
appName = evt.target.getAttribute("appName");
}
You could check if something is undefined by doing this (Copied from here):
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof always returns a string. Also, there's a difference between comparing with "double equals" and "triple equals" so you might want to check this out.
I have provided the sample snippet.
you have tried evt.target.getAttribute instead try evt.getAttribute
Try like this.
function findAttr(e){
if (!e.hasAttribute("appName")) {
console.log("No attribute");
} else {
console.log(e.getAttribute("appName"));
}
}
<div onclick="findAttr(this)">is attr present?</div>
<div onclick="findAttr(this)" appName="test">is attr present?</div>
If you have an alternate state for your element determined by the presence/absence of an attribute then use .toggleAttribute()
function editMode(e) {
const clicked = e.target;
const editor = document.querySelector('.editor');
if (clicked.matches('.mode')) {
clicked.classList.toggle('on');
clicked.classList.toggle('off');
editor.toggleAttribute('contenteditable');
if (clicked.matches('.off')) {
editor.focus();
} else {
editor.blur();
}
}
return false;
}
document.querySelector('.mode').onclick = editMode;
.editor {
min-height: 32px
}
.mode {
float: right;
display: inline-block;
width: 100px;
}
.on::before {
content: 'READ/WRITE';
}
.off::before {
content: 'READ ONLY';
}
<fieldset class='editor'></fieldset>
<button class='mode on'></button>
Related
So I'm trying to edit this rss feed with these 2 functions because of the media:content property which I have had no luck accessing directly. the functions I have below work for creating a new value called mediaContent which I can then easily access. The issue is in the rss feed not all objects will have media:content and I want to add a default value for the objects that don't have that property so I have consistency in my objects. Otherwise I end up with undefined on on some of mediaContent in my new object. I wanted to start just added a default value in when media:content is not present in the object but these ||'s are not working as I would have expected. How can I get my else if to punch in a default value if media:content does not exist? I'm probably missing something easy.
function getMediaContent(value) {
for (var i in value) {
if (i === "media:content") {
console.log("MC::", i)
return value[i].$;
} else if (i !== "title" || i !== "link" || i !== "pubDate" || i !== "isoDate" || i !== "guid" || i !== "contentSnippet" || i !== "content") {
debugger;
return "no media content"
}
}
}
function getNewsLinks() {
return newsItems.map(value => ({
value,
mediaContent: getMediaContent(value)
}))
}
SOLUTION (based on accepted answer)
function getMediaContent(value) {
return "media:content" in value ? value["media:content"].$ : "no media content";
}
works perfectly. Thanks!
Since you're just looking to see if a property exists on an object, you can use the in operator:
function getMediaContent(value) {
return "media:content" in value ? value["media:content"].$ : "no media content";
}
That checks if the property exists, and if so, gets the value of its $ property. Otherwise, returns the default value.
I needed something similar and optionally it would work for multi-layered JSON objects. Here is the function I use:
function getFromJSON(obj, ...args) {
for (const arg of args) {
if (!Array.isArray(arg)) {
if (arg in obj) {
obj = obj[arg]
} else {
return `${arg} not found in JSON`;
}
} else {
for (const argOpt of arg) {
if (argOpt in obj) {
obj = obj[argOpt]
break;
}
}
}
}
return obj
}
In addition, you can pass multiple keys in an array if you want to get the value of whichever exists.
https://jsfiddle.net/3vz45os8/7/
I've got this jsfiddle where I want to change the background color of the input text in a specific color if the word is well type and in another one if the word is not well type. It's currently doesn't work but I got no error in the console. If u guys could help me.
This is the js function, I log every step and didn't get an error:
function isCorrect() {
var test = document.getElementById('test').value;
if (test.value === "hello") {
test.classname = "correct"
return true;
} else {
test.classname = "incorrect"
return false;
}
}
var test = document.getElementById('test').value;
if (test.value === "hello") {
You're calling .value twice. Take it off the first line, because otherwise you'll be adding className (which should be camel-cased by the way) to a string value instead of the input element.
Here is the corrected code and a working copy:
function isCorrect() {
var test = document.getElementById('test');
if (test.value === "hello") {
test.className = "correct";
return true;
} else {
test.className = "incorrect";
return false;
}
}
It's correctly adding the class, but your CSS is being overridden so I just removed the default color for illustration.
You're doubling up on values:
var test = document.getElementById('test').value;
^^^^^^
if (test.value === "hello") {
^^^^^^
test is ALREADY the value of that input, which means it's a plain string. A string has no .value attribute, so you're doing undefined === "hello".
Also use className not classname
^ ^
You have a few errors:
The keyword is className not classname. Please change that.
You are already getting the .value. No need to call it again.
Corrected Code:
function isCorrect() {
var test = document.getElementById('test').value;
if (test === "hello") {
test.className = "correct"
//------------^
return true;
} else {
test.className = "incorrect"
//------------^
return false;
}
}
if (authorID) {
console.log(authorID);
$.ajax({
-ajax stuff-
)}
} else window.location.href="notLoggedIn.html";
ok this is my problem: in console authorID (a String) does get printed and it's printed as null.
My question is: why does this happen? Since authorID is null shouldn't be the else block the one executed?
I'm really new to Javascript/jQuery so I think i may just have missed some obvious thing, but wasn't able to figure it myself.
edit: here's how authorID is created:
if (session.getAttribute("authorID")!= null) {
authorID = session.getAttribute("authorID").toString();
}
since i'm testing without logging in i'm expecting session.getAttribute() to return null
Well, JavaScript is a very flexible language. It is very easy to get confused by "truthy" values.
null and false belong to those truthy common mistakes.
Somewhere before your method execution, a null value was converted into string. Maybe if you get the value from the DOM.
That's why on debug, you see "null" being written to the output. But in reality you have "null" as a string not the raw value of null.
for JavaScript this is evaluates to true:
if("null"){
}
The only way to eliminate this is to make a check of the datatype using typeof and check against the correct value.
if(a !== null && a !== "null"){
}
Ok, the problem is that a string always evaluates as true. You have said authorID is a string; therefore if (authorID) will always evaluate true.
What you can do is test if your 'authorID' string does not equal 'null':
if (authorID !== 'null')
I imagine you want the page redirection to happen only when 'authorId' equals the string 'null, so your code would look like this:
if (authorID !== 'null') {
console.log(authorID);
$.ajax({
// -ajax stuff-
)}
} else {
window.location.href = "notLoggedIn.html";
}
Alternatively, now that you've edited the question to show how 'authorID' is defined:
Change that block to:
if (session.getAttribute("authorID")) {
authorID = session.getAttribute("authorID").toString();
} else {
authorID = null;
}
Then you can use your original conditional:
if (authorID) {
console.log(authorID);
$.ajax({
// -ajax stuff-
)}
} else {
window.location.href = "notLoggedIn.html";
}
I would suggest having a read of: http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html
In your case, the end of that article shows the mistake you've made:
if (foo == null) {
foo = "Joe";
}
Is equal to:
if (!foo) {
foo = "Joe";
}
I did a quick jsfiddle that I hope will spell it out better for you: http://jsfiddle.net/vp9Fa/1/
to pass the if condition authorID should be initialized as a boolean variable.
var authorID=true;
if (authorID)
{
//code if true
}
else
{
//code if false
}
in your code you can do like below
if (authorID!=null)
{
//code if not null
}
else
{
//code if null
}
I don't want to know if an element contains a specific class, but just if it's loaded in DOM:
$(myObject).attr("class").length;
or
if($t.classList.length) {
var classSUP = $t.attr("class");
} else {
var classSUP = $t.attr("id");
};
Or how about just
(myObject.className != '')
or, just to be sure about possible additional spaces
(myObject.className.replace(' ', '') != '')
This is no job for a framework ;)
The easiest way to check would be:
if($("element").attr("class")) {
return true;
}
Example shown here: http://jsfiddle.net/Skooljester/XpUJA/
You don't need jQuery to do this:
if (element.className) {
// element has a class
}
or, if you really want to use jQuery:
if ($('#elementID').attr('class')) {
// element has a class
}
Try this:
var containsClass = $t.attr("class") !== "" && $t.attr("class") !== undefined;
Here is as a function:
function containsClass($t)
{
return $t.attr("class") !== "" && $t.attr("class") !== undefined;
}
The easiest way to detect if particular object loaded in DOM is:
if ( $('.className').length ) {
alert('.className is on DOM')
}
I need to check if thevar[2] === 'debug' however thevar[2] might be undefined so if I ran the following code with it being undefined javascript would throw an error:
if (thevar[2] === 'debug') {
console.log('yes');
}
So what I'm currently doing is:
if (typeof thevar[2] !== 'undefined') {
if (thevar[2] === 'debug') {
console.log('yes');
}
}
Is this really the best way to do this?
Your first example will not throw an error. Undefined properties of objects evaluate to undefined, but they don't throw errors.
var foo = {};
var nothing = foo.bar; // foo.bar is undefined, so "nothing" is undefined.
// no errors.
foo = [];
nothing = foo[42]; // undefined again
// still no errors
So, your second example is not needed. The first is sufficient.
If you can run if (typeof thevar[2] !== 'undefined') ... then you can reference thevar and you can run anything else with it.
If your array exists then checking against a value works fine, even if that value is undefined.
> var x = [];
undefined
> if ( x[0] === "debug" ) console.log("yes");
undefined
> if ( x[100] === "debug" ) console.log("yes");
undefined
The issue arises only when the array doesn't already exist. So as long as you know thevar has value then no check needed. Otherwise just check if thevar has value or do a little var assignment trick like
var thevar = thevar || [];
//work with thevar with impunity