根据浏览器中显示的文本选择按钮元素

时间:2015-03-20 10:07:41

标签: javascript jquery html dom

在JavaScript中我试图根据显示的文本选择html按钮,而不是他们的类或id,因为它们都是相同的。
所有按钮都具有相同的dom结构和类。因此它们在浏览器中显得不同,我不知道如何区分。

我发现的最好的例子是在twitter上:
您有followunfollow按钮 但是如果你检查它中的dom元素,它们都是完全相同的。

<button class="user-actions-follow-button js-follow-btn follow-button btn" type="button">
  <span class="button-text follow-text">
     <span class="Icon Icon--follow"></span> Follow
  </span>
  <span class="button-text following-text">
     Following
  </span>
  <span class="button-text unfollow-text">
     Unfollow
  </span>
  ...
</button>

我不知道如何在那里做出区分,我觉得这应该是可能的,因为你可以用眼睛来看待差异。

我在不同搜索引擎中搜索了很多但没有结果。获取我找到的元素的唯一方法是基于dom结构,例如getElementsByClassNamegetElementById:contains(),在我的示例中没有用。

也许这是故意不可能的,在这种情况下我不会进一步搜索(并认为这是最好的答案)。

非常感谢!

编辑: 我不能使用jQuery

3 个答案:

答案 0 :(得分:1)

尝试使用以下代码,您可以相应地设置样式

$( "span:nth-child(1):contains('Following')" ).css( "background", "#ccc" );

答案 1 :(得分:0)

你可以按如下方式给出id:

  <span id="follow" class="button-text following-text">
     Following
  </span>
  <span id="unfollow" class="button-text unfollow-text">
     Unfollow
  </span>

然后在javascript中使用以下代码,您可以检查其状态

if(document.getElementById("follow").innerHTML=="Following"){
//follow 
}
if(document.getElementById("unfollow").innerHTML=="Unfollow"){
//unfollow 
}

答案 2 :(得分:0)

我找到了使用:hidden的方法,但这是jQuery,因此在我的情况下没用。

$('span:hidden:contains(Follow)').parent();

我现在发现的最好的事情是首先获取所有按钮,然后使用条件(需要2个步骤,但正在工作)。

var buttons=document.getElementsByClassName('...');
//loop...
    if ( window.getComputedStyle(buttons[i].getElementsByClassName('...')[0] ).display === 'none' ) {
        //buttons[i]
    }

如果您找到更好的解决方案,仍然欢迎: - )