Categories
JavaScript Answers

How to get first element of a collection that matches iterator function with JavaScript?

To get first element of a collection that matches iterator function with JavaScript, we use the array find method.

For instance, we write

const array = [5, 12, 8, 130, 44];
const found = array.find((element) => element > 10);
console.log(found);

to call array.find with a function that returns the first element in array that’s bigger than 10.

ASs a result, found is 12.

Categories
JavaScript Answers

How to get HTML element via aria label with JavaScript?

To get HTML element via aria label with JavaScript, we use the querySelector or querySelectorAll methods.

For instance, we write

const element = document.querySelector('[aria-label="Message Body"]');

to select the first element with the aria-label attribute set to Message Body.

Likewise, we write

const list = document.querySelectorAll('[aria-label="Message Body"]');

to select all the elements with the aria-label attribute set to Message Body returned in a node list.

Categories
JavaScript Answers

How to set the background-color of a D3.js svg with JavaScript?

To set the background-color of a D3.js svg with JavaScript, we can call attr to set the class attribute.

For instance, we write

const svg = d3
  .select("body")
  .append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .attr("class", "graph-svg-component");

to select the body element with select.

And then we call append to append the svg as the last child of the body element.

Next, we call attr to set the class attribute to the graph-svg-component class.

And then we add

.graph-svg-component {
  background-color: green;
}

into the CSS file to apply styles for the class.

Categories
JavaScript Answers

How to push to a JavaScript multidimensional array?

To push to a JavaScript multidimensional array, we call the push method.

For instance, we write

cookieValue.push([productID, itemColorTitle, itemColorPath]);

to call cookieValue.push with an array with the items we want to append the array into the cookieValue array.

Categories
JavaScript Answers

How to fix ‘gapi is not defined’ error with JavaScript Google sign in?

To fix ‘gapi is not defined’ error with JavaScript Google sign in, we should make sure the auth2 object is initialized before calling init.

For instance, we write

const initSigninV2 = async () => {
  const authInstance = await gapi.auth2.init({
    client_id: "CLIENT_ID.apps.googleusercontent.com",
  });
  //...
};

gapi.load("auth2", initSigninV2);

to call init in the initSigninV2 function.

init returns a promise with the auth object.

And then we make sure initSigninV2 is called only after the auth2 object is loaded by calling load with 'auth2' and initSigninV2 as its callback.