Categories
JavaScript Answers

How to append HTML to container element without innerHTML with JavaScript?

To append HTML to container element without innerHTML with JavaScript, we call the insertAdjacentHTML method.

For instance, we write

const d1 = document.getElementById("one");
d1.insertAdjacentHTML("beforeend", '<div id="two">two</div>');

to select the container element with getElementById.

And then we call insertAdjacentHTML method with 'beforeend' and a string with the element to insert.

'beforeend' inserts the HTML as the last child of the container element.

Categories
JavaScript Answers

How to add options to select with JavaScript?

To add options to select with JavaScript, we use the Option constructor.

For instance, we add a select element with

<select id="ageSelect">
  <option value="">Please select</option>
</select>

Then we write

const selectElement = document.getElementById("ageSelect");

for (let age = 12; age <= 100; age++) {
  selectElement.add(new Option(age));
}

to select the select element with getElementById.

Then we use a for loop to loop through the age values and then create a new option element with the Option constructor called with its text content value.

Then we call selectElement.add to add the option as the last child of the select drop down.

Categories
JavaScript Answers

How to disable dragging an image from an HTML page with JavaScript?

To disable dragging an image from an HTML page with JavaScript, we stop the default action for the dragstart event.

For instance, we write

document.getElementById("my-image").ondragstart = () => {
  return false;
};

to select the img element with getElementById.

Then we set its ondragstart property to a function that returns false to stop the default drag action to stop the img element from being dragged.

Categories
JavaScript Answers

How to show or hide ‘div’ using JavaScript?

To show or hide ‘div’ using JavaScript, we set the div’s style.display property.

For instance, we write

element.style.display = "none";

to hide the element by setting element.style.display to 'none'.

We write

element.style.display = "block";

To show the element as a block element by setting element.style.display to 'block'.

Or we write

element.style.display = "inline";

To show the element as an inline element by setting element.style.display to 'inline'.

Or we write

element.style.display = "inline-block";

To show the element as an inline block element by setting element.style.display to 'inline-block'.

Categories
JavaScript Answers

How to get the parent div of element with JavaScript?

To get the parent div of element with JavaScript, we use the parentNode property.

For instance, we write

const parentDiv = pDoc.parentNode;

to get the parent div element of the pDoc element with the parentNode property.