Zentie
Zentie

Reputation: 97

js find Elements with same innerHTML

I have a button that has some text and I get that text by innerHTML

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

Then I have a few other buttons that trigger accordion boxes

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

I would like to select one element from helpAccordions that matches helpName and set it as a 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>

Upvotes: 0

Views: 93

Answers (2)

Joe Lissner
Joe Lissner

Reputation: 2472

If you can't use jQuery, I made a fiddle showing it working, below is the relevant code.

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

Upvotes: 1

prasanth
prasanth

Reputation: 22500

Simply use with jquery contains()

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

})
<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>

Upvotes: 1

Related Questions