Categories
JavaScript Answers

How to remove an item from a select box with JavaScript?

To remove an item from a select box with JavaScript, we use the remove method.

For instance, we write

<select name="selectBox" id="selectBox">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>
</select>

to add the select drop down.

Then we write

document.querySelector("#selectBox option[value='option1']").remove();

to select the option element in the drop down with the value attribute set to option1 with querySelector.

And then we call remove to remove the option.

Categories
JavaScript Answers

How to add/remove several classes in one single instruction with classList and JavaScript?

To add/remove several classes in one single instruction with classList and JavaScript, we can call add or remove with all the classes we want to add or remove.

For instance, we write

elem.classList.add("first", "second", "third");

to call elem.classList.add to add the first, second, and third classes.

Likewise, we write

elem.classList.remove("first", "second", "third");

to call elem.classList.remove to remove the first, second, and third classes.

Categories
JavaScript Answers

How to get the values of data attributes in JavaScript?

To get the values of data attributes in JavaScript, we use the dataset property of the element.

For instance, we write

const id = document.querySelector("html").dataset.pbUserId;

to select the html element with querySelector.

And then we use the dataset property to get the value of the data-pbUserId attribute of the element.

Categories
JavaScript Answers

How to change div content with JavaScript?

To change div content with JavaScript, we set the div’s innerHTML property.

For instance, we write

document.getElementById("content").innerHTML = "whatever";

to select the div with getElementById.

And then we set its innerHTML property to the content of it.

Categories
JavaScript Answers

How to convert HTML string into DOM elements with JavaScript?

To convert HTML string into DOM elements with JavaScript, we use the DOMParser constructor.

For instance, we write

const xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
const doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML);

to create a DOMParser object and call the parseFromString method with the xmLString and the MIME type.

Then we get the first child element’s HTML code with doc.firstChild.innerHTML.