Add class to specific multiple SPAN's

问题: I want to add class to multiple SPAN (but not all SPAN). In this case i'm choosing to add class to last 2 SPAN's. So currently my code is taking a string and then insert...

问题:

I want to add class to multiple SPAN (but not all SPAN). In this case i'm choosing to add class to last 2 SPAN's.

So currently my code is taking a string and then inserting each letter as SPAN in html.

So then i want the code to read the last 2 (or any other amount) of span to add another .class (in this case .blue)

I believe this is part of the code i need to use, but because i'm doing += it add another extra SPAN to html which is causing duplicates.

if (i >= 5) {
    html += '<span class="blue blast">' + split[i] + '</span>';
}

Full code here and CodePen:

function myFunction() {
    var string = document.querySelector('.title').innerHTML
    var split = string.split('');
    var html = '';

    for (let i = 0; i < split.length; i++) {
        html += '<span class="blast">' + split[i] + '</span>';

        if (i >= 5) {
            html += '<span class="blue blast">' + split[i] + '</span>';
        }

    }

    document.querySelector('.title').innerHTML = html;
}
myFunction()

https://codepen.io/MariusZMM/pen/MZdpNb

I already have jQuery code that does this for me. But i want to learn Vanila JavaScript.

Update: with the help from tymeJV i have updated CodePen with a fix: https://codepen.io/MariusZMM/pen/pqmwgL


回答1:

You only want to write the blue letters when i > 5 - so wrap the other portion in an else block

    if (i >= 5) {
        html += '<span class="blue blast">' + split[i] + '</span>';
    } else {
        html += '<span class="blast">' + split[i] + '</span>';
    }

回答2:

This is my proposition:

function myFunction(num) {
  const splitted = document.querySelector('.title').innerHTML.split('');

  const newContent = splitted.map((letter, i) => {
    const className = i >= splitted.length - num ? 'blue blast' : 'blast';

    return '<span class="'+className+'">' + letter + '</span>';
  }).join('');

  document.querySelector('.title').innerHTML = newContent;
}

myFunction(3);
  • 发表于 2019-01-18 18:46
  • 阅读 ( 102 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除