如何使用jQuery在元素内设置纯文本样式?

时间:2019-01-09 15:40:12

标签: jquery

使用jQuery的.css()方法,如何为以下HTML结构中每个列表项的之后 span.foo设置纯文本样式?

具体来说,我需要在每个span.foo之后获得文本(不知道它是什么),并将其涂成红色。

<li>
    not this text
    <span class='foo'>not this text</span>
    this text
</li>
<li>
    not this text
    <span class=“foo”>not this text</span>
    and this text
</li>
<li>
    not this text
    <span class='foo'>not this text</span>
    and this text as well
</li>

$().css('color', 'red');

3 个答案:

答案 0 :(得分:2)

您将必须选择跨度,然后需要在其后选择文本元素。要设置样式,您需要将其包装在另一个元素中。

$('ul li span').each( (i, elem) => { // function (i, elem) {
   $(elem.nextSibling).wrap('<span class="special"/>')
});

  
.special {
  color: #CFC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
    not this text
    <span class='foo'>not this text</span>
    this text
</li>
<li>
    not this text
    <span class=“foo”>not this text</span>
    and this text
</li>
<li>
    not this text
    <span class='foo'>not this text</span>
    and this text as well
</li>
</ul>

答案 1 :(得分:0)

不确定这是否100%正确,因为jQuery会更改html,但是您无需从源头更改html(我认为这是声明的根据)。

$(function () {
    $("li").each(function (item) {
        $(this).contents().filter(function () {
            return this.nodeType === 3;
        }).last().wrap("<span class='text-red'></span>");
    });
});
.text-red {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<li>
    not this text
    <span class='foo'>not this text</span>
    this text
</li>
<li>
    not this text
    <span class=“foo”>not this text</span>
    and this text
</li>
<li>
    not this text
    <span class='foo'>not this text</span>
    and this text as well
</li>

答案 2 :(得分:0)

这需要花点时间,因为它是原始文本节点,而不是元素,而是这里。

自然地,要为节点设置样式,我们需要将其包装在某些东西中。我选择了一个内联样式的匿名跨度。

$("span.foo").each(function() {
  var node = this.nextSibling;
  if (node.nodeType == 3) { // see if the next node is actually a text node
    var $el = $("<span>")
      .text(node.textContent)
      .css("color", "orange"); // create a wrapper element and style it
    node.replaceWith($el[0]); // replace the text node with our new span element.
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>
  not this text
  <span class='foo'>not this text</span> this text
</li>
<li>
  not this text
  <span class="foo">not this text</span> and this text
</li>
<li>
  not this text
  <span class='foo'>not this text</span> and this text as well
</li>