I have 2 issues:
- Array split functionality as I cannot use it not sure why?
- Words are not highlighting.
const text = [
`Jelly sweet roll jelly beans biscuit pie macaroon chocolate donut. Carrot cake caramels pie sweet apple pie tiramisu carrot cake. Marzipan marshmallow croissant`
]; // this is what i want to use instead of 'p' but also below not working
function selectWord() {
//const p = document.querySelector('p');
text.innerHTML = text.innerText
.split('')
.map((word) =>
word.length > 5 ? `<span class="lightext">${word}</span>` : word
)
.join('');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.lightext {
background-color: yellow;
}
</style>
</head>
<body>
<p>This is the extremely long paragraph that we want to highlight all words longer than eight characters in.</p>
</body>
<script src="app1.js"></script>
</html>
>Solution :
I simply fixed the obvious bugs in your code. Most notably, splitting words on spaces (where you had an empty string) and then reassembling them by the same.
function selectWord() {
const p = document.querySelector('p');
console.log(p.innerText.split(' '));
p.innerHTML = p.innerText
.split(' ')
.map((word) =>
word.length > 5 ? `<span class="lightext">${word}</span>` : word
)
.join(' ');
}
selectWord();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.lightext {
background-color: yellow;
}
</style>
</head>
<body>
<p>This is the extremely long paragraph that we want to highlight all words longer than eight characters in.</p>
</body>
<script src="app1.js"></script>
</html>