简体   繁体   English

将段落文本更改为风格化跨度

[英]Changing Paragraph Text to Stylized Span

I'm trying to change paragraph text in a for each loop.我正在尝试更改每个循环中的段落文本。 This seems like a simple issue (specific to JS?).这似乎是一个简单的问题(特定于 JS?)。 I'm new to this language, coming from Matlab and Java.我是这种语言的新手,来自 Matlab 和 Java。 Fiddle attached.附上小提琴。 Any help is appreciated.任何帮助表示赞赏。

https://jsfiddle.net/npkx3of4/1/ https://jsfiddle.net/npkx3of4/1/

function myFunction() {
    var ps = document.getElementsByClassName('.test');
    for (var p of ps) {
        p = p.replace('a', '<span style="color:blue;">b</span>');
    }
    alert("Working?");
    return null;
}
  1. getElementsByClassName('.test') should be getElementsByClassName('test') . getElementsByClassName('.test')应该是getElementsByClassName('test')

  2. You should be assigning the result of replacing the innerHTML of the paragraph back to the innerHTML of the paragraph.您应该将替换段落的innerHTML的结果分配回该段落的innerHTML

 function myFunction() { var ps = document.getElementsByClassName('test'); for (var p of ps) { p.innerHTML = p.innerHTML.replace('a', '<span style="color:blue;">b</span>'); } alert("Working?"); return null; }
 <h1>Test</h1> <hr> <p class="test">a</p> <button type="button" onclick='myFunction();'>Click Me!</button>

There isn't any need to add a period before the class name when using getElementsByClassName .使用getElementsByClassName时,无需在 class 名称之前添加句点。

var ps = document.getElementsByClassName('test');

Select only the plain text content inside the element, then replace all the specified characters before rewriting the inner HTML. Select 仅是元素内部的纯文本内容,然后在重写内部 HTML 之前替换所有指定的字符。

...  
    for (var p of ps) {
        p.innerHTML = p.textContent.replaceAll('a', '<span style="color:blue;">b</span>');
    }
...

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

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