Skip to content Skip to sidebar Skip to footer

Target One Letter In A String With Javascript

Suppose I have this string: 'hello' in a tag, and I want to execute a code for each letter (example: hide, change opacity, etc..). How can I make this with JS/Jquery w

Solution 1:

No and yes. As far as I know, no, a span tag around each letter is necessary, but, yes, you can swing it in JavaScript. A couple examples here, using this concept to randomly apply a color and size to each character.

forEach loop method: JSFiddle

<span>hello</span><script>var span = document.querySelector('span')
var str = span.innerHTML
span.innerHTML = ''
str.split('').forEach(function (elem) {
    var newSpan = document.createElement('span')
    newSpan.style.color = "#"+((1<<24)*Math.random()|0).toString(16)
    newSpan.style.fontSize = (Math.random() * (36 - 10) + 10) + 'px'
    newSpan.innerHTML = elem
    span.appendChild(newSpan)
})

</script>

dynamically styled hello


setTimeout method: JSFiddle

<span>hello</span><script>var span = document.querySelector('span')
var str_arr = span.innerHTML.split('')
span.innerHTML = ''var ii = 0
~functioncrazy(ii, str_arr, target) {
    if ( ii < str_arr.length ) {
        var newSpan = document.createElement('span')
        newSpan.style.color = "#"+((1<<24)*Math.random()|0).toString(16)
        newSpan.style.fontSize = (Math.random() * (72 - 36) + 36) + 'px'
        newSpan.innerHTML = str_arr[ii]
        target.appendChild(newSpan)
        setTimeout(function () {
            crazy(ii += 1, str_arr, target)
        }, 1000)
    }
}(ii, str_arr, span)

</script>

enter image description here

Solution 2:

You can do this.

In html

<span id="my-text">hello</span>
<div id="split-span" ></div>

In Javascript,

var text = $('#my-text').html().split('');

for(var i=0; i<text.length; i++){
    $('#split-span').append('<span>'+text[i]+'</span>');
}

Solution 3:

You can do this fairly easily in vanilla javaScript without the need of a library like jquery. You could use split to convert your string into an array. This puts each letter into an index of the array. From here you can add markup to each index (or letter) with a loop.

example:

var str = "hello";
   var res = str.split(''); 

   for( var i = 0; i < res.length; i++ ){
     res[ i ] = '<span>' + res[ i ] + '</span>'
   }

Post a Comment for "Target One Letter In A String With Javascript"