Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Highlight the word in array

I have 2 issues:

  1. Array split functionality as I cannot use it not sure why?
  2. 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading