Categories
JavaScript Answers

How to Check if an Element Exists in the Visible DOM with JavaScript?

document.body.contains

We can use the document.body.contains method checks if an element is part of the visible DOM.

For instance, we can write the following HTML:

<div>  
  hello world  
</div>

And then we can check if the div is in the visible DOM by writing:

const div = document.querySelector('div')  
const isVisible = document.body.contains(div)  
console.log(isVisible)

We get the element with querySelector and pass it into the contains method.

And we see that the console log logs true if it’s visible on the page.

contains is available with anything other than Internet Explorer.

document.documentElement.contains

Instead document.body.contains , we can use document.documentElement.contains to do the same check.

For instance, we can write:

const div = document.querySelector('div')  
const isVisible = document.documentElement.contains(div)  
console.log(isVisible)

to do the check on the div.

And we should get the same result as before.

Check the parentNode Property

Another way to check if an element is in the visible DOM is to check if the parentNode property is truthy.

If it is, then we know the element is in the visible DOM.

For instance, we can write:

const div = document.querySelector('div')  
const isVisible = Boolean(div.parentNode)  
console.log(isVisible)

We just pass the div.parentNode property straight into the Boolean function to return true if it’s truthy and false otherwise.

And so we should see that the console log is true if we have the same HTML as in the first example.

Check the baseURI Property

Another property we can check to see if an element is in the visible DOM is in the baseURI property.

For instance, we can write:

const div = document.querySelector('div')  
const isVisible = Boolean(div.baseURI)  
console.log(isVisible)

to do the check.

If div.baseURI is truthy, then it’s in the DOM.

Otherwise, it’s not.

Categories
JavaScript Answers

How to Remove All Line Breaks From a JavaScript String?

String.prototype.replace

We can call the replace method with a regex to search for all line breaks in a string and replace them all with empty strings to remove the line breaks.

For instance, we can write:

const trimmed = 'abc\r\ndef'.replace(/(\r\n|\n|\r)/gm, "");
console.log(trimmed)

to remove all the line breaks.

\r and \n are the patterns for the line breaks.

g lets us search the whole string for all instances of line break characters.

Therefore trimmed is 'abcdef' .

We can also use the control code character equivalent in place of \r and \n by writing:

const trimmed = 'abc\r\ndef'.replace(/\[^\x20-\x7E\]/gmi, "")
console.log(trimmed)

\x20 is equivalent to \r .

And \x7E is equivalent to \n .

String.prototype.trim

The trim method lets us remove all line break characters from the start and end of a string.

For instance, we can write:

const trimmed = 'abc\r\n'.trim()
console.log(trimmed)

Then trimmed is 'abc' .

String.prototype.trimStart

The trimStart method lets us remove all line break characters from the start of a string.

For instance, we can write:

const trimmed = '\r\nabc'.trimStart()
console.log(trimmed)

Then trimmed is 'abc' .

String.prototype.trimEnd

The trimEnd method lets us remove all line break characters from the end of a string.

For instance, we can write:

const trimmed = 'abc\r\n'.trimEnd()
console.log(trimmed)

Then trimmed is 'abc' .

Categories
JavaScript Answers

How to Calculate Text Width with JavaScript?

Sometimes, we’ve to calculate the width of text content in our JavaScript code.

In this article, we’ll look at how to calculate text content width in our JavaScript code.

clientHeight and clientWidth

The clientHeight and clientWidth properties of an HTML element object lets us get the height and width of the element.

Therefore, we can write the following HTML:

<p id='text'>  
  hello world  
</p>

to create the element.

Then we can write the JavaScript coder to get the height and width of the element:

const fontSize = 12;  
const text = document.getElementById("text");  
text.style.fontSize = fontSize;  
const height = text.clientHeight  
const width = text.clientWidth  
console.log(height, width);

We get the p element with getElementById .

Then we use the clientHeight and clientWidth propetties to get the height and width of the p element respectively.

Then we log that with the console.

We should get something like:

18 222

from the console log.

The numbers are in pixels.

Canvas.measureText Method

The HTML canvas element has the measureText method that lets us measure the size of a piece of text.

This means that we can put our text into the canvas and then call that to measure its size.

For instance, we can write:

const text = 'hello world'  
const font = "bold 12pt arial"  
const canvas = document.createElement("canvas");  
const context = canvas.getContext("2d");  
context.font = font;  
const {  
  width  
} = context.measureText(text);  
console.log(width)

We have the text and font variables with the text content and font styles respectively.

Then we create a canvas with createElement .

And we call getContext to get the context.

Next, we set the font property with the font styles.

And then we call measureText with the text variable to measure the size of text .

We get the width property from the returned object.

And we should see a number like 84.4453125 logged from the console log.

The number is also in pixels.

Conclusion

We can either measure text size with the clientHeight and clientWidth properties of an element.

Also, we can put our text into the canvas and use the measureText method to measure the text width.

Categories
JavaScript Answers

How to Find the Max value of a Property in an Array of JavaScript Objects?

Sometimes, we’ve to find the max value of a property in an array of JavaScript objects.

In this article, we’ll look at how to find the max value of an attribute in an array of JavaScript objects.

Math.max

The Math.max method is a static method that lets us find the max value from all the arguments that are passed in.

For instance, we can write:

const array = [{
    "x": "8/11/2021",
    "y": 0.026572007
  },
  {
    "x": "8/12/2021",
    "y": 0.025057454
  },
  {
    "x": "8/13/2021",
    "y": 0.024530916
  },
  {
    "x": "8/14/2021",
    "y": 0.031004457
  }
]
const max = Math.max(...array.map(o => o.y))
console.log(max)

We call array.map to return an array with the y property values from each object in the array.

Then we use the spread operator to spread all the values into the Math.max method as arguments.

Then we get that max is 0.031004457 since this is the biggest value in the whole list.

Array.prototype.reduce

The reduce method lets us compute a result from an array of items.

We can use it to find the max value of a property in the array.

For instance, we can write:

const array = [{
    "x": "8/11/2021",
    "y": 0.026572007
  },
  {
    "x": "8/12/2021",
    "y": 0.025057454
  },
  {
    "x": "8/13/2021",
    "y": 0.024530916
  },
  {
    "x": "8/14/2021",
    "y": 0.031004457
  }
]
const maxObj = array.reduce((prev, current) => (prev.y > current.y) ? prev : current)
console.log(maxObj.y)

We call reduce with a callback that has the prev and current parameters.

prev has the result computed so far.

current has the current value of array being iterated through.

We return the object with the bigger y value in the callback.

Therefore, it should return the object with the biggest y value in the end.

And maxObj.y should be the same as max in the previous example.

Array.prototype.sort

Another way to find the max y value from the array of items is to sort the array in descending order with sort .

For example, we can write:

const array = [{
    "x": "8/11/2021",
    "y": 0.026572007
  },
  {
    "x": "8/12/2021",
    "y": 0.025057454
  },
  {
    "x": "8/13/2021",
    "y": 0.024530916
  },
  {
    "x": "8/14/2021",
    "y": 0.031004457
  }
]
const [{
  y: max
}] = array.sort((a, b) => b.y - a.y)
console.log(max)

We call array.sort with a callback that returns b.y — a.y .

a and b are objects in array being compared.

If the callback’s return value is positive, then the order of the items are switched.

Otherwise, they stay the same.

We destructure the y value from the first element on the left side and set it as the value of max .

And max has the same value as the previous examples.

Conclusion

We can find the max value of a property from an array of JavaScript objects with various array methods or the Math.max method with the spread operator.

Categories
JavaScript Answers

How to Get Distinct Values From an Array of Objects in JavaScript?

Sometimes we may want to get distinct values from an array of objects in our JavaScript code.

In this article, we’ll look at how to get distinct values from an array of objects in JavaScript.

Extracting Values with Array Methods

One way to get distinct values from an array of objects in JavaScript is to use native array methods.

For instance, we can write:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = array.map(item => item.age)
  .filter((value, index, self) => self.indexOf(value) === index)
console.log(uniques)

to call the map and filter to return unique values of the age property from all the items in the array.

We call map to return an array with all the age values.

Then we use filter to return an array with distinct values of the age value array returned from map .

The callback we pass into filter has the value , index and self parameters.

value has the value being iterated through.

index has the index of the value .

And self is the array itself.

We can check if it’s the first instance of a given value with self.indexOf(value) === index .

indexOf returns the index of the first instance of value in the array.

So we can use that return an array that only has the first instance of a given element.

Therefore uniques is [17, 35] .

We can replace the filter call by putting the age value array in a set and then spreading that back into an array:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = [...new Set(array.map(item => item.age))]
console.log(uniques)

And uniques has the same value as the previous example.

The spreading can be replaced with the Array.from method:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = Array.from(new Set(array.map(item => item.age)))
console.log(uniques)

since Array.from works with any iterable objects, including sets, to convert them into an array.

Lodash

Lodash has the uniq method to return unique values from an array of objects.

So we can use it by writing;

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = _.uniq(_.map(array, 'age'));
console.log(uniques)

We call map to return an array of age values from array .

And then we call uniq on the returned array to get the unique values from that returned array.

So we get the same result for uniques as the other examples.

Conclusion

We can use native JavaScript array methods or Lodash to extract distinct values from a property from an array of objects.