Exploring methods to determine if an element possesses a certain attribute without explicitly analyzing the element itself

Attempting to generate a query object when clicking on different buttons by passing attributes in the HTML called "attr-{{foo}}" that are derived from an ng-repeat or other methods. I intended for the controller to first check if the element has all the attributes that correspond to the keys of the query object in the scope, and then gradually go down the chain to having only one attribute; but when I attempted this, I kept encountering the error "cannot find .value of 'null'", especially during testing with

(below is a snippet resembling my controller)

 vm.openFoos = function (event) {
 if (event.target.attributes.getNamedItem('attr-foo').value && 
  !event.target.attributes.getNamedItem('attr-bar').value) {
  var obj = {
    foo: event.currentTarget.attributes.getNamedItem('attr-foo').value,
    name: $routeParams.name
  } else if {
  (event.target.attributes.getNamedItem('attr-foo').value && 
   event.target.attributes.getNamedItem('attr-bar').value) {
  var obj = {
    foo: event.currentTarget.attributes.getNamedItem('attr-foo').value,
    name: $routeParams.name,
    bar: event.currentTarget.attributes.getNamedItem('attr-bar').value
   }
  }
  data.getReviews(obj)
    .success(function (data){$log.debug(data)}).error(function(e){$log.debug(e)}); 
};

This logic works when clicking on elements with both attr-foo and attr-bar (based on the specific order of checking from most strict case of having attributes to least), as switching the order of the if statements would result in the "cannot find value of null" error. Sample HTML:

<span class="one" ng-click="vm.openFoos($event) attr-foo="foooo">Click FOOO</span>

<span class="two" ng-click="vm.openFoos($event) attr-foo="fo" attr-bar="bar">Click FOO BAR</span>

When clicking span.one, it triggers the "cannot find value of null" error, whereas clicking span.two works correctly. I don't want to create a separate controller for each unique combination of keys in my query that appear in different HTML attributes, yet I'm still facing this issue.

Answer №1

Instead of relying on

if (event.currentTarget.attributes.getNamedItem('attr-thing').value ....

Try using

if (event.currentTarget.attributes.getNamedItem('attr-thing') ....

In cases where

event.currentTarget.attributes.getNamedItem('attr-thing')

Is not present, extracting its value becomes impossible!

Answer №2

Have you considered using hasOwnProperty?

object.hasOwnProperty("attrname"); // Returns true or false.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring data visualization through object classification in Angular JS

I am facing a scenario where my API returns a single JSON Object if there is only one element in the response, and an array of objects if there are more than one elements. This poses a challenge as I need to handle both cases without changing the JSON stru ...

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...

The latest version of Ionic seems to be having trouble with the iframe tag

I recently completed a tutorial on using the Ionic framework to develop mobile apps. The tutorial, which can be found here: , was very helpful and I was able to build an app successfully following the steps provided. However, when I tried to add a feature ...

Remove the option to delete without making any changes to the flash file

Utilizing the DataTable javascript tool to export a grid, I have obtained the following HTML generated code: <div class="DTTT_container"> <a class="DTTT_button DTTT_button_copy" id="ToolTables_example_0" tabindex="0" aria-controls="e ...

Encountering a type error when attempting to assign an interface to a property

In my Angular project, I am working with typescript and trying to assign the IInfoPage interface to some data. export interface IInfoPage { href: string; icon: string; routing: boolean; order: number; styleType: string; ...

A variety of personalized Vimeo play buttons

Recently, I stumbled upon a genius solution by Chris Coyier for creating custom Vimeo play buttons. It worked perfectly for my needs, but now I'm facing a challenge - how to make it function with multiple videos on the same page. I tried swapping out ...

Utilizing ReactJS onBlur event for email field validation

Currently, I am using a MaterialUI Textfield for email input validation upon leaving the field. To achieve this, I have implemented a function triggered when the onBlur event occurs. My intention is to display an error message using helpertext. Here' ...

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

Uninstalling NPM License Checker version

Utilizing the npm license checker tool found at https://www.npmjs.com/package/license-checker The configuration in license-format.json for the customPath is as follows: { "name": "", "version": false, "description&quo ...

VueJs Ellipsis Filter: Enhance Your Texts with

Using Vue.JS, I am dynamically injecting text content into a DOM element. <article>{{ movie.summary }}</article> My goal is to implement an auto-ellipsis filter. Essentially, the code would look like this: <article>{{ movie.summary | e ...

Using MySQL and PHP, implementing a feature that generates lines on Google Maps by fetching coordinates from a database

I have an idea to develop a navigation application where I need to draw a line connecting two points stored in a Database. The line starts from the starting point, goes through a fixed point defined in the code, and ends at the destination point. To achi ...

How can I identify the moment when an AngularJS route controller is no longer in scope?

Currently, I have a controller set up to poll the server at regular intervals using $timeout. The issue arises when the route changes - I need to stop the polling and then restart it once the original route is accessed again. If anyone has any suggestions ...

Firebase9 cloud storage encountered an issue: [Unhandled promise rejection: ReferenceError: Property 'storage' doesn't exist]

I'm encountering the following issue: [Unhandled promise rejection: Invariant Violation: Failed to construct File: Must pass both parts and name arguments.] I am attempting to upload an image to Firebase cloud storage by selecting it on my phone. T ...

Exploring AngularJS: Custom directive for accessing the min attribute value of an input[date] element

I am attempting to gain write access to the <input type="date" min attribute from within my custom directive value. I am aware that the input[date] element is a directive as well. You can read more about it at this link. Using $(elem).attr('min&apo ...

Transform HTML into PNG with Canvas2image, followed by the conversion of PNG into BMP

Is there a direct way to convert HTML to BMP? After searching online, it seems that there isn't a straightforward method. So, I decided to convert HTML to PNG using canvas JS and then use PHP to convert the file from PNG to BMP. I have a question abou ...

Update the URL using JQuery and Ajax without having to reload the page, ensuring compatibility with Internet Explorer versions 8 and 9

Upon the initial loading of my webpage, it directs to the following URL: /default/ After clicking the "nextPost" button on the screen (which includes an attribute named data-nextPostNumber), the corresponding code is as follows: event.preventDefault(); ...

Typescript does not produce unused members

Having an issue with the JS code that TypeScript compiler is generating. Here's an example class: // Class export class UserDTO { Id: number; FirstName: string; LastName: string; DateOfBirth: Date; getFullName(): string { ...

Transfer the document to the server using ajax

I've been attempting to upload an image to the server using the following simple code: <form enctype="multipart/form-data"> <input name="file" type="file" /> <input type="button" value="Upload" /> </form> <progress ...

Oops! There was an unhandled error: TypeError - Unable to retrieve property 'data' as it is undefined

I'm encountering an issue while working on my vue.js project. Uncaught (in promise) TypeError: Cannot read property 'data' of undefined Let's take a look at the code snippet where the error is happening. In this piece of code, I am ...

Generate fresh JavaScript objects with customized properties

My goal is to use Javascript and JQuery to automatically create a new object with properties provided by the user when they fill out an HTML form. I have a constructor named "object" for this purpose. function object (prop1, prop2, prop3) { this.p ...