Categories
JavaScript Answers

How to get an element’s id with JavaScript?

To get an element’s id with JavaScript, we use the id property.

For instance, we write

const id = myDOMElement.id;

to get the myDOMElement‘s ID with the id property.

Categories
JavaScript Answers

How to disable form auto submit on button click with JavaScript?

To disable form auto submit on button click with JavaScript, we return false in the form submit event handler.

For instance, we write

myForm.onsubmit = () => {
  // ...
  return false;
};

to set the myForm.onsubmit property to a function that returns false to prevent the default form submission behavior.

Categories
JavaScript Answers

How to get selected option text with JavaScript?

To get selected option text with JavaScript, we can use the selectedIndex property.

For instance, we write

<select id="box1" onChange="onChange(this);">
  <option value="98">dog</option>
  <option value="7122">cat</option>
  <option value="142">bird</option>
</select>

to add a select drop down.

We set the onchange attribute to call onChange with the select element.

Then we write

function onChange(sel) {
  console.log(sel.options[sel.selectedIndex].text);
}

to define the onChange function.

We get the selected option with sel.options[sel.selectedIndex].

And we get the option’s text with the text property.

Categories
JavaScript Answers

How to link a JavaScript file to a HTML file?

To link a JavaScript file to a HTML file, we add a script element.

For instance, we write

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

to add the script element to load jQuery in our HTML code.

Categories
JavaScript Answers

How to clear all div’s contents inside a parent div with JavaScript?

To clear all div’s contents inside a parent div with JavaScript, we set innerHTML to an empty string.

For instance, we write

document.getElementById("masterdiv").innerHTML = "";

to select the outer div with getElementById.

And then we set its innerHTML property to an empty string to clear its contents.