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.
Web developer specializing in React, Vue, and front end development.
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.
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.
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.
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.
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.