Reputation: 57194
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.
Is this the proper way to handle this?
Upvotes: 0
Views: 7669
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
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
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