js找到具有相同innerHTML的元素

时间:2017-03-30 12:35:59

标签: javascript jquery html innerhtml

我有一个带有一些文字的按钮,我通过innerHTML获得该文本

var helpName = helpButton.parentElement.querySelector('span').innerHTML;

然后我有一些触发手风琴盒的其他按钮

var helpAccordions = modal.getElementsByClassName('accordion');

我想从helpAccordions中选择一个与helpName匹配的元素,并将其设置为var。

    <div class="modal-content">
        <span class="close">&times;</span>
        <h3 class="modal-title">Help</h3>

        <button class="accordion">Key Partners</button>
    </div>

    <div class="section-header">
        <span>Key Partners</span>
        <div class="help-icon"></div>
    </div>

2 个答案:

答案 0 :(得分:1)

只需使用jquery contains()

&#13;
&#13;
$(document).ready(function (){
$('button').click(function(){
var a = $('span:Contains('+$(this).text()+')').parent();
//result varible is a
console.log(a.attr('class'))
})

})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="modal-content">
        <span class="close">&times;</span>
        <h3 class="modal-title">Help</h3>

        <button class="accordion">Key Partners</button>
    </div>

    <div class="section-header">
        <span>Key Partners</span>
        <div class="help-icon"></div>
    </div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果你不能使用jQuery,我会让fiddle显示它正常工作,下面是相关代码。

var helpName = helpButton.parentElement.querySelector('span').innerHTML;
var helpAccordions = modal.getElementsByClassName('accordion');
var length = helpAccordions.length;

var myButton;
for(var i = 0; i < length; i++) {
    var button = helpAccordions[i];
    if(button.innerHTML === helpName) {
        myButton = button;
        break;
    }
}
console.log(myButton) // the button with Key Partners as the text