我如何使用jQuery或Javascript来定位div的第二个字母

时间:2017-10-25 04:13:23

标签: javascript jquery

美好的一天,

如何定位通过API获取值的div的第二个字母。

<div>example</div>

示例是通过API获取的数据,我想在其上的第二个字母中添加样式。我怎么能这样做?

5 个答案:

答案 0 :(得分:1)

以下是示例:

var string = $('div').text(), t;

/*  
    1st letter - string.substr(0,1)
    2nd letter - string.substr(1,1) 
    2nd onwards - string.substr(2)
*/
t = string.substr(0,1) + '<span class="test">'+ string.substr(1,1) + '</span>' + string.substr(2);
   
console.log(t);
$('div').html(t);
.test{
 color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>example</div>

答案 1 :(得分:1)

您可以拆分将创建字符数组的字符串,然后在指定的索引处添加HTML标记和字符。使用join再次创建字符串并使用replace方法替换逗号('

// creating an array the characters
var splitString = document.getElementById('textContent').innerHTML.split('');
// targeting the character at index 1
splitString[1] = '<span class ="custom">x</span>'
document.getElementById('textContent').innerHTML = splitString.join('').replace(/,/g, '')
.custom {
  color: red
}
<div id="textContent">example</div>

答案 2 :(得分:1)

您可能想知道CSS中有一个::first-letter伪元素,但遗憾的是它无法帮助您。它只适用于块级元素。

&#13;
&#13;
var divs = document.querySelectorAll('div');

for (var el of divs) {
  var text = el.textContent;
  el.innerHTML = text[0] + '<span>' + text[1] + '</span>' + text.substring(2);
}
&#13;
span {
  color: red;
}
&#13;
<div>example1</div>
<div>example2</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用prototype将index中的char替换为样式内容。

&#13;
&#13;
String.prototype.replaceAt=function(index, replaceChar) {
    var a = this.split("");
    a[index] = replaceChar;
    return a.join("");
}

var result ="example";
var secondChar = result.charAt(1);
var updatedContent = result.replaceAt(1, '<span class="test">'+secondChar+'</span>');
console.log(updatedContent);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您可以在数组对象上使用splice在特定索引中插入元素,在本例中为1.索引3第二次因为索引移动了一个位置。

arr.splice(index, 0, item)会将项目插入到指定索引的arr中(首先删除0项,也就是说,它只是一个插入)。 Found it here

var str = document.getElementById('test').innerText().split('');
str.splice(1, 0, '<span class="colored">');
str.splice(3, 0, '</span>');
document.getElementById('test').innerText = str.join('');
.colored {
 color: blue;
}
<div id='test'>example</div>