如何更改特定标签的内容?

时间:2017-05-04 09:18:44

标签: javascript jquery css

我正在尝试更改特定标签的内容。我现在有这个,但它没有用。

<label for="product_configure_variants">Make a choice: <em>*</em></label>

...

<style>
label:before[for="product_configure_variants"]{content: "my new content"!important;}
</style>

任何人都可以帮忙取悦它吗?将“选择:”更改为“我的新内容”。

2 个答案:

答案 0 :(得分:1)

您可以在标签上设置font-size: 0以隐藏其文字,然后再次更改embefore伪元素的字体大小以显示它们,同时您的选择器也是错误的。

label[for="product_configure_variants"] {
  font-size: 0;
}
label[for="product_configure_variants"]:before {
  content: "my new content";
  font-size: 16px;
}
label em {
  font-size: 16px;
}
<label for="product_configure_variants">Make a choice: <em>*</em></label>

您还可以使用js并选择label的内容,并检查nodeType是3还是text,如果index是0,则将其删除。

$('label[for="product_configure_variants"]').contents().each(function(i) {
  if(i == 0 && this.nodeType == 3) $(this).remove()
})
label[for="product_configure_variants"]:before {
  content: "my new content";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="product_configure_variants">Make a choice: <em>*</em></label>

答案 1 :(得分:1)

可以通过以下方式完成:

  

选项1:只需在标签中添加一个类,然后执行以下操作:

<强> HTML:

    <label for="product_configure_variants" class="my-label">Make a choice: <em>*</em></label>

<强> JS:

    $('.my-label').text('My new Content');

Demo

  

选项2 :通过label和属性for进行访问。

<强> HTML:

<label for="product_configure_variants">Make a choice: <em>*</em></label>

<强> JS:

$('label[for="product_configure_variants"]').text('My new Content');

Demo