Categories
JavaScript Answers

How to Use document.getElementById with Multiple IDs in JavaScript?

Sometimes, we want to use document.getElementById with Multiple IDs in JavaScript

In this article, we’ll look at how to use document.getElementById with Multiple IDs in JavaScript

Use document.getElementById with Multiple IDs in JavaScript

To use document.getElementById with Multiple IDs in JavaScript, we can replace document.getElementById with document.querySelector.

For instance, if we have:

<div id='myCircle1'>
  circle
</div>
<div id='myCircle2'>
  circle
</div>
<div id='myCircle3'>
  circle
</div>
<div id='myCircle4'>
  circle
</div>

Then we write:

const circles = document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4")
console.log(circles)

We call document.querySelectorAll with a string that has the selector of all the elements separated by a comma.

And then we assign the returned result to circles.

Therefore, circles is a node list with the 4 elements we selected.

Conclusion

To use document.getElementById with Multiple IDs in JavaScript, we can replace document.getElementById with document.querySelector.

Categories
JavaScript Answers

How to Copy a Text String on Click with JavaScript?

Sometimes, we want to copy a text string on click with JavaScript.

In this article, we’ll look at how to copy a text string on click with JavaScript.

Copy a Text String on Click with JavaScript

To copy a text string on click with JavaScript, we can call the document.execuCommand to copy the text to the clipboard.

Then we can listen to the copy event to get the copied text.

For instance, if we have:

<span>hello world</span>

Then we write:

const span = document.querySelector("span");

span.onclick = () => {
  document.execCommand("copy");
}

span.addEventListener("copy", (event) => {
  event.preventDefault();
  if (event.clipboardData) {
    event.clipboardData.setData("text/plain", span.textContent);
    console.log(event.clipboardData.getData("text"))
  }
});

We select the span element with document.querySelector.

Then we set the span.onclick property to a function that calls document.execCommand with 'copy' to copy the text content of the span.

Next, we call span.addEventListener with 'copy' to add a copy event listener.

The callback will run when we run document.execCommand("copy");.

We get the clipboard data with the event.clipboardData.setData to set the copied data to the textContent of the span.

And then we can get the text data that’s copied to the clipboatd with the getData method with 'text'.

Conclusion

To copy a text string on click with JavaScript, we can call the document.execuCommand to copy the text to the clipboard.

Then we can listen to the copy event to get the copied text.

Categories
JavaScript Answers

How to Sort a JavaScript Array by ISO 8601 Date?

Sometimes, we want to sort a JavaScript array by ISO 8601 date.

In this article, we’ll look at how to sort a JavaScript array by ISO 8601 date.

Sort a JavaScript Array by ISO 8601 Date

To sort a JavaScript array by ISO 8601 date, we can use the JavaScript array’s sort method.

For instance, we can write:

const arr = [{
    name: 'oldest',
    date: '2001-01-17T08:00:00Z'
  },
  {
    name: 'newest',
    date: '2011-01-28T08:00:00Z'
  },
  {
    name: 'old',
    date: '2009-11-25T08:00:00Z'
  }
];

const sorted = arr.sort((a, b) => {
  return (a.date < b.date) ? -1 : ((a.date > b.date) ? 1 : 0)
});
console.log(sorted)

We have the arr array that we want to sort by the date value.

Then we call arr.sort with a callback that compares the strings to compare the date strings directly by their values lexigraphically.

If a.date is less than b.date we return keep their order.

Otherwise, if a.date is bigger than b.date, we return 1 to reverse their order.

If they’re the same, we return 0.

Therefore, sorted, is:

[
  {
    "name": "oldest",
    "date": "2001-01-17T08:00:00Z"
  },
  {
    "name": "old",
    "date": "2009-11-25T08:00:00Z"
  },
  {
    "name": "newest",
    "date": "2011-01-28T08:00:00Z"
  }
]

Conclusion

To sort a JavaScript array by ISO 8601 date, we can use the JavaScript array’s sort method.

Categories
JavaScript Answers

How to Convert JavaScript Object to URL Parameters?

Sometimes, we want to convert JavaScript object to URL parameters.

In this article, we’ll look at how to convert JavaScript object to URL parameters.

Convert JavaScript Object to URL Parameters

To convert JavaScript object to URL parameters, we can use the jQuery.params method.

For instance, we write:

const params = {
  width: 1000,
  height: 800
};
const str = jQuery.param(params);
console.log(str);

We have the params object with the width and height properties.

Then we call jQuery.params method with the params object as its argument.

And then we assigned the returned query string to str.

From the console log, we should see that str is 'width=1000&height=800'.

Conclusion

To convert JavaScript object to URL parameters, we can use the jQuery.params method.

Categories
JavaScript Answers jQuery

How to Remove Whitespace and Line Breaks between HTML Elements Using jQuery?

Sometimes, we want to remove whitespace and line breaks between HTML elements using jQuery.

In this article, we’ll look at how to remove whitespace and line breaks between HTML elements using jQuery.

Remove Whitespace and Line Breaks between HTML Elements Using jQuery

To remove whitespace and line breaks between HTML elements using jQuery, we can use the filter method to remove any items that are whitespace in the selected items list.

For instance, if we have:

 <div id="widget">        <h2>foo</h2><p>hi.</p>        </div>

Then we write:

jQuery.fn.cleanWhitespace = function() {
  this.contents().filter(
      function() {
        return (this.nodeType == 3 && !/\S/.test(this.nodeValue));
      })
    .remove();
  return this;
}

const widget = $('#widget').cleanWhitespace();
console.log(widget.contents())

We add the cleanWhitespace method to the jQuery object to remove all the selected items that are whitespaces.

In the method, we call this.contents to get the selected contents.

Then we call filter with a callback that returns the nodes with nodeType 3, which are text nodes, and nodes that aren’t whitespaces only, which we check with the regex.

Then we call remove to remove the nodes returned by filter.

And finally we return this.

Next, we select the div with $ and call cleanWhitespace on it.

And finally, we call widget.contents and should see that there are no whitespace nodes left.

Conclusion

To remove whitespace and line breaks between HTML elements using jQuery, we can use the filter method to remove any items that are whitespace in the selected items list.