Categories
JavaScript Answers

How to get element by name with JavaScript?

To get element by name with JavaScript, we use the getElementsByName method.

For instance, we write

const val = document.getElementsByName("acc")[0].value;

to select the first element with name attribute acc with

document.getElementsByName("acc")[0]

Then we get its value with the value property.

Categories
JavaScript Answers

How to correctly iterate through getElementsByClassName with JavaScript?

To correctly iterate through getElementsByClassName with JavaScript, we use a for-of loop.

For instance, we write

const slides = document.getElementsByClassName("slide");
for (const slide of slides) {
  console.log(slide);
}

to call getElementsByClassName to select all elements with class slide.

Then we use a for-of loop to loop through all the slides and log its value.

Categories
JavaScript Answers

How to do something before on submit with JavaScript?

To do something before on submit with JavaScript, we call preventDefault in the submit handler.

For instance, we write

<form id="formId" action="/" method="POST" onsubmit="prepareForm(event)">
  <input type="text" value="" />
  <input type="submit" value="Submit" />
</form>

to add a form.

We set the onsubmit attribute to call the prepareForm function.

Then we write

function prepareForm(event) {
  event.preventDefault();
  // ...
  document.getElementById("formId").requestSubmit();
}

to define the prepareForm function.

In it, we call preventDefault to stop the default submit behavior.

And then we select the form with getElementByid and call requestSubmit to submit the form.

Categories
JavaScript Answers

How to get a number of random elements from an array with JavaScript?

To get a number of random elements from an array with JavaScript, we use the array sort and Math.random methods.

For instance, we write

const shuffled = array.sort(() => 0.5 - Math.random());
const selected = shuffled.slice(0, n);

to call sort to returned a shuffled version of the array by calling it with a function that returns a random number.

Then we get an array with the first n items in the shuffled array with slice.

Categories
JavaScript Answers

How to place div element at center of screen with CSS?

To place div element at center of screen with CSS, we use flexbox.

For instance, we write

<html>
  <head> </head>
  <body>
    <div class="center-screen">I'm in the center</div>
  </body>
</html>

to add a div.

Then we write

.center-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 100vh;
}

to make the div a flex container with display: flex;.

Then we set its flex direction to vertical with flex-direction: column;.

We horizontally center its content with align-items: center;.

And we vertically center its content with justify-content: center;.