Categories
JavaScript Answers

How to Convert RGB Color Code to Hex with JavaScript?

Sometimes, we want to convert RGB color code to hex with JavaScript.

In this article, we’ll look at how to convert RGB color code to hex with JavaScript.

Convert RGB Color Code to Hex with JavaScript

To convert RGB color code to hex with JavaScript, we can get the RGB number values with the JavaScript string match method.

Then we can match each value to the corresponding hex number and join them together with the JavaScript string’s join method.

For instance, we write:

const RGBtoHEX = (color) => {
  return "#" + [...color.match(/\b(\d+)\b/g)]
    .map((digit) => {
      return parseInt(digit)
        .toString(16)
        .padStart(2, '0')
    })
    .join('');
};

console.log(RGBtoHEX('rgb(0, 70, 255)'))

We call color.match with /\b(\d+)\b/g to match the RGB color values from the color syring.

Then we use the spread operator to spread the returned results into an array.

Next, we call map with a callback to parse the numbers into integers, then we convert then to hex strings with toString and 16 as its argument.

Then we call padStart to pad the returned string with a zero to make its length 2.

Finally, we call join to join the mapped strings together.

Therefore, the console log should show "#0046ff".

Conclusion

To convert RGB color code to hex with JavaScript, we can get the RGB number values with the JavaScript string match method.

Then we can match each value to the corresponding hex number and join them together with the JavaScript string’s join method.

Categories
JavaScript Answers

How to Check if Any Div Contain a Word with JavaScript?

Sometimes, we want to check if any div contains a word with JavaScript.

In this article, we’ll look at how to check if a any div contains a word with JavaScript.

Check if Any div Contains a Word with JavaScript

To check if a div contains a word with JavaScript, we can select all the divs and then loop through them with the for-of loop.

Then we can get the text content of each div in the loop body using the textContent property.

And then we can check if the div includes the text we’re looking for with the JavaScript string’s includes method.

For instance, if we have:

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

Then we can check which div has the word ‘bar’ in it by writing:

const divs = document.querySelectorAll('div')
for (const d of divs) {
  if (d.textContent.includes('bar')) {
    console.log('has bar')
  }
}

We select all the divs and assign it to divs with:

const divs = document.querySelectorAll('div')

Then we loop through the node list object we assigned to divs by writing:

for (const d of divs) {
  if (d.textContent.includes('bar')) {
    console.log('has bar')
  }
}

We get the text content of each div with d.textContent.

Then we call includes with 'bar' to check if the text content of the div includes 'bar'.

If that’s true, we log 'has bar'.

Therefore, we should see 'has bar' logged once in the console since ‘bar’ appears in one div.

Conclusion

To check if a div contains a word with JavaScript, we can select all the divs and then loop through them with the for-of loop.

Then we can get the text content of each div in the loop body using the textContent property.

And then we can check if the div includes the text we’re looking for with the JavaScript string’s includes method.

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.