Categories
JavaScript Answers

How to Open All a Links on a Page in New Windows with JavaScript?

Sometimes, we want to open all a links on a page in new windows with JavaScript.

In this article, we’ll look at how to open all a links on a page in new windows with JavaScript.

Open All a Links on a Page in New Windows with JavaScript

To open all a links on a page in new windows with JavaScript, we can set the target attribute of all the a elements to _blank.

For instance, if we have:

<a href='https://google.com'>google</a>
<a href='https://yahoo.com'>yahoo</a>
<a href='https://bing.com'>bing</a>

Then we write:

const links = document.querySelectorAll('a')
for (const l of links) {
  l.target = '_blank'
}

We select all the a elements with document.querySelectorAll and assign the select the node list of elements to links.

Then we use the for-of loop to loop through all the links and set the target attribute to _blank by setting the target property to '_blank'.

Now the links should all open on a new tab.

Conclusion

To open all a links on a page in new windows with JavaScript, we can set the target attribute of all the a elements to _blank.

Categories
JavaScript Answers

How to Get the Second Match of a Selector with document.querySelector?

Sometimes, we want to get the second match of a selector with the document.querySelector method.

In this article, we’ll look at how to get the second match of a selector with the document.querySelector method.

Get the Second Match of a Selector with document.querySelector

To get the second match of a selector with the document.querySelector method, we can use the nth-child pseudo-selector.

For instance, if we have:

<div class='titanic'>
  foo
</div>
<div class='titanic'>
  bar
</div>
<div class='titanic'>
  baz
</div>

Then we can select the 2nd element with class titanic by writing:

const second = document.querySelector('.titanic:nth-child(2)')
console.log(second)

We use nth-child(2) to select the 2nd match.

Therefore, second should be the div with ‘bar’ as the text content.

Conclusion

To get the second match of a selector with the document.querySelector method, we can use the nth-child pseudo-selector.

Categories
JavaScript Answers

How to Generate an XML Document In-Memory with JavaScript?

Sometimes, we want to generate an XML document in-memory with JavaScript.

In this article, we’ll look at how to generate an XML document in-memory with JavaScript.

Generate an XML Document In-Memory with JavaScript

To generate an XML document in-memory with JavaScript, we can use varioud methods built into modern browsers.

For instance, we write:

const doc = document.implementation.createDocument(null, "report", null);

const submitterElement = doc.createElement("submitter");
const nameElement = doc.createElement("name");
const name = doc.createTextNode("John Doe");

nameElement.appendChild(name);
submitterElement.appendChild(nameElement);
doc.documentElement.appendChild(submitterElement);

console.log((new XMLSerializer()).serializeToString(doc))

We create an empty XML document with the document.implementation.createDocument method:

const doc = document.implementation.createDocument(null, "report", null);

Then we create a few nodes with the createElement method:

const submitterElement = doc.createElement("submitter");
const nameElement = doc.createElement("name");
const name = doc.createTextNode("John Doe");

Next, we call appendChild to append the name text node to the name element.

We append the nameElement to the submitterElement next.

And finally we append the submitterElement to the document root with:

nameElement.appendChild(name);
submitterElement.appendChild(nameElement);
doc.documentElement.appendChild(submitterElement);

Finally, we get the string version of the XML document and log it with:

console.log((new XMLSerializer()).serializeToString(doc))

Now we get:

<report>
   <submitter>
      <name>John Doe</name>
   </submitter>
</report>

logged into the console as a result.

Conclusion

To generate an XML document in-memory with JavaScript, we can use varioud methods built into modern browsers.

Categories
JavaScript Answers

How to Flatten an Array with Objects into 1 Object with JavaScript?

To flatten an array with objects into 1 object with JavaScript, we can use the Object.assign method with the spread operator.

For instance, we write:

const arr = [{ a: 1 }, { b: 2 }, { c: 3 }]
const merged = Object.assign(...arr);
console.log(merged)

We have the arr array with multiple objects inside.

Then we call Object.assign with all the arr entries as arguments by spreading them into the Object.assign method.

It returns an object with the properties of all the objects merged in.

This is then assigned to merged.

Therefore, merged is:

{
  a: 1,
  b: 2,
  c: 3
}
Categories
JavaScript Answers

How to Use the Fetch API to Get an Image from a URL?

Sometimes, we want to use fetch API to Get an image from a URL.

In this article, we’ll look at how to use fetch API to Get an image from a URL.

Use the Fetch API to Get an Image from a URL

To use fetch API to Get an image from a URL, we can call the blob method on the response object.

Then we can use FileReader to read the blob into a base64 string.

For instance, we write:

const imageUrl = "https://i.picsum.photos/id/566/200/300.jpg?hmac=gDpaVMLNupk7AufUDLFHttohsJ9-C17P7L-QKsVgUQU";

(async () => {
  const response = await fetch(imageUrl)
  const imageBlob = await response.blob()
  const reader = new FileReader();
  reader.readAsDataURL(imageBlob);
  reader.onloadend = () => {
    const base64data = reader.result;
    console.log(base64data);
  }
})()

We call fetch with imageUrl to make a GET request to the imageUrl and return a promise with the response object.

Then we call response.blob to return a promise with the blob data of the image.

Next, we create a FileReader instance and set the onloadend property to a function that gets the base64 string from the blob with the reader.result property.

And then we log the base64data value in the console.

Conclusion

To use fetch API to Get an image from a URL, we can call the blob method on the response object.

Then we can use FileReader to read the blob into a base64 string.