替换同名类的内部div中的span文本

时间:2017-11-08 13:37:45

标签: javascript jquery html css

我有一个像

这样的DOM元素
<div class="gm-style-cc">
    <div>
        <div></div>
        <div></div>
    </div><span>some text</span>
    <div>
        <a target="_new">Report a map error</a>
    </div>
</div>
<div class="gm-style-cc">
    <div>
        <span>5000 km</span>
    </div>
</div>

我想在第二个范围内将km替换为里程,但我甚至无法访问特定范围

首先我尝试改变颜色, 我尝试了以下内容,但没有得到确切的值

.gm-style-cc:nth-child(1) span {  color: yellow !important; }
.gm-style-cc:nth-child(2) span {  color: green !important; }
.gm-style-cc:nth-child(3) span {  color: green !important; }

----------
span.gm-style-cc:nth-child(1) {  color: yellow !important; }

----------
.gm-style-cc:nth-of-type(1).eq(1) div span{
    color: red !important;
}

-------
.gm-style-cc span{
   color: red !important;
}

-----------
.gm-style-cc:nth-of-type(1).eq(1) div span{
    color: red !important;
}

如何获得span元素的具体位置?

编辑:正如Mazz所建议的那样

.gm-style-cc div span {
    color: red;
}

似乎显示了变化,但它正在为所有范围做,我想要在第二类中使用跨度

3 个答案:

答案 0 :(得分:3)

使用jQuery,您可以执行以下操作。

$('.gm-style-cc div span').css( 'color', 'red' );

仅适用于第二个.gm-style-cc

$('.gm-style-cc').eq(1).find('div span').css('color', 'red');

这也适用于css

.gm-style-cc div span {
    color: red;
}

/* for only the second .gm-style-cc */ 
.gm-style-cc:eq(2) div span {
    color: red;
}

如果来自第三方库,您可能需要添加!important

更改为内容:

var sp = $('.gm-style-cc div span');
var value = $('.gm-style-cc div span').text().split(' ');
var newValue = value[0]/1.609344;
sp.text(newValue + ' miles');

答案 1 :(得分:1)

您可以使用基本JavaScript查找元素,并将km替换为miles

以下代码将搜索span .gm-style-cc内的所有div,并在其文本中包含一个后跟km的数字,然后执行需要更换:

// Selecting all spans that are inside .gm-style-cc divs
var elms = document.querySelectorAll(".gm-style-cc span");

Array.prototype.forEach.call(elms, function(elm) {

  // Check if the text of the element contains a number followed by "km"
  if (elm.innerText.search(/\d+ km/) !== -1) {

    // Converting km to miles
    miles = Number(elm.innerText.split(" ")[0]);
    miles = miles * 0.621371;

    // Creating the new contents
    elm.innerText = String(miles) + " miles";

  }
})
<div class="gm-style-cc">
  <div>
    <div></div>
    <div></div>
  </div><span>some text</span>
  <div>
    <a target="_new">Report a map error</a>
  </div>
</div>
<div class="gm-style-cc">
  <div>
    <span>5000 km</span>
  </div>
</div>

答案 2 :(得分:0)

试试这个[编辑]

    (function(){

$('.gm-style-cc').find("span:contains('km')").each(function(i,ele){
        var miles = (parseInt($(this).text(),10) / 1.609344) + ' miles';
        $(ele).text(miles)
 })


})();
相关问题