[英]Add class to specific multiple SPAN's
I want to add class to multiple SPAN (but not all SPAN). 我想将类添加到多个SPAN(但不是所有SPAN)。 In this case i'm choosing to add class to last 2 SPAN's.
在这种情况下,我选择将类添加到最后2个SPAN。
So currently my code is taking a string and then inserting each letter as SPAN in html. 因此,当前我的代码使用一个字符串,然后将每个字母作为SPAN插入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) 所以然后我希望代码读取跨度的最后2个(或任何其他数量)以添加另一个.class(在这种情况下为.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. 我相信这是我需要使用的代码的一部分,但是因为我在做+ =,所以它会向html添加另一个额外的SPAN,从而导致重复。
if (i >= 5) {
html += '<span class="blue blast">' + split[i] + '</span>';
}
Full code here and CodePen: 完整代码在这里和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 https://codepen.io/MariusZMM/pen/MZdpNb
I already have jQuery code that does this for me. 我已经有jQuery代码可以为我执行此操作。 But i want to learn Vanila JavaScript.
但是我想学习Vanila JavaScript。
Update: with the help from tymeJV i have updated CodePen with a fix: https://codepen.io/MariusZMM/pen/pqmwgL 更新:在tymeJV的帮助下,我已使用以下修补程序更新了CodePen: https ://codepen.io/MariusZMM/pen/pqmwgL
You only want to write the blue letters when i > 5
- so wrap the other portion in an else
block 您只想在
i > 5
时写蓝色字母-将其他部分包裹在else
块中
if (i >= 5) {
html += '<span class="blue blast">' + split[i] + '</span>';
} else {
html += '<span class="blast">' + split[i] + '</span>';
}
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.