简体   繁体   English

将第一个字符转换为大写时出错

[英]Error convert first character to upper case

I want to convert the first characters of all the span tags to upper case but i am getting an error: TypeError: a[0].toUpperCase is not a function. 我想将所有span标签的第一个字符转换为大写,但我收到一个错误:TypeError:a [0] .toUpperCase不是一个函数。

 <div id="test"> <h1> <span>test</span> <span>test</span> <span>test</span> </h1> </div> 

 var x = document.getElementById("test"); function capital(a) { return a[0].toUpperCase() + a.slice(1); } 

 var test=x.getElementsByTagName("span"); var b=capital(test) console.log(b) 

getElementsByTagName("span") return a HTMLCollection . getElementsByTagName("span")返回一个HTMLCollection So if you want to use toUpperCase() , you need to loop through it and call innerText . 因此,如果你想使用toUpperCase() ,你需要遍历它并调用innerText

 var x = document.getElementsByTagName("span"); console.log(x) function capital(a){ return a[0].toUpperCase() + a.slice(1); } for(el of x) { el.innerText = capital(el.innerText); } 
 <div id="test"> <h1> <span>test</span> <span>test</span> <span>test</span> </h1> </div> 

You should use text-transform css property: 你应该使用text-transform css属性:

 span { text-transform: capitalize; } 
 <div id="test"> <h1> <span>test</span> <span>test</span> <span>test</span> </h1> </div> 

you can do it by applying querySelecterAll on the span tag and then convert the textcontent to the uppercase 您可以通过在span标记上应用querySelecterAll然后将textcontent转换为大写来实现

 let myVal = document.querySelectorAll('span') let arr=Object.values(myVal); arr.map(m=>{ let c=m.textContent; let text=c.charAt(0).toUpperCase() +c .slice(1) m.textContent=text; } ) 
 <div id="test"> <h1> <span>test1</span> <span>test2</span> <span>test3</span> </h1> </div> 

your were trying to convert element to uppercase, you need to get the text form the DOM then convert it. 你试图将元素转换为大写,你需要从DOM获取文本然后转换它。 Using innerHTML or textContent to get text from the element will solve your problem. 使用innerHTMLtextContenttextContent中获取文本将解决您的问题。

Here we go 开始了

 let x = document.getElementById('test'); // your main element let span = x.getElementsByTagName('SPAN'); // all span element within x for( let char of span ) { // you should Add innerHTML in order to get the text console.log(char.innerHTML[0].toUpperCase() + '' + char.innerHTML.slice(1)); } 
 <div id="test"> <h1> <span>test</span> <span>test</span> <span>test</span> </h1> </div> 

Best practice to wrap the console each time when your write a single line code! 每次编写单行代码时最好的做法是包装控制台!

Cheer you! 为你加油!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM