Xeoncross
Xeoncross

Reputation: 57194

Using Javascript to hide words in a string

I have a sentence which I would like to be able to hide words by using Javascript. For example, hiding the first and 6th word or something. Coming from a PHP background my guess is that it would go something like this.

  1. You have a DIV with a sentence in it.
  2. You get the value of the DIV (the text sentence).
  3. You split the text by spaces " " to get each word.
  4. You then surround each word with a SPAN and id or class.
  5. You place all the words with the spans around them back into the DIV.
  6. Then from user interaction (or timeout events) you can hide each SPAN[text]SPAN as needed.

Is this the proper way to handle this?

Upvotes: 0

Views: 7669

Answers (3)

Christoph
Christoph

Reputation: 169603

I'd do it exactly as you described. In fact, I actually did:

<div>
The dog jumps over the log.
</div>
<script type="text/javascript">
function boxWords(textNode) {
    var frag = document.createDocumentFragment(),
        // trim leading and trailing whitespace to avoid empty elements
        words = textNode.nodeValue.replace(/(^\s+)|(\s+$)/g, '').split(' ');

    for(var i = 0, len = words.length; i < len; ++i) {
        frag.appendChild(document.createElement('span').appendChild(
            document.createTextNode(words[i])).parentNode);
        frag.appendChild(document.createTextNode(' '));
    }

    textNode.parentNode.replaceChild(frag, textNode);
}

var div = document.getElementsByTagName('div')[0];
boxWords(div.firstChild);

// underline the 4th word
div.getElementsByTagName('span')[3].style.textDecoration = 'underline';
</script>

Upvotes: 1

Patrick
Patrick

Reputation: 7712

I think the general idea makes sense yes...

Get the innerhtml of the div.. split it by " " and then for each word in the value put it into a div with a unique id... you can keep the relative size of the word in the space by making invisible, or you can make the sentence collapse by making the innerhtml = "".

function divclick(id)
{
    //document.getElementById(id).style.visibility="hidden";
        // OR 
    //document.getElementById(id).innerHTML = "";
}

As for getting the div split and re-displayed into its own individual word divs... that shouldnt be to big of a deal... the only think you have to take into consideration is what events are causing the words to dissappear or appear.

Upvotes: 0

Steerpike
Steerpike

Reputation: 17554

I not sure what purpose steps 4->6 serve? If you got the seperated words in step 3 then you can retain that array and always have access to the appropriate word when you need to do something with it.

Your way you still have to figure out which span/id/class to mess with when you want to do something. You're essentially creating the same problem for yourlsef in a different format,

Upvotes: 0

Related Questions