Tyler Zika Tyler Zika - 3 months ago 14
Javascript Question

Get all global attribute values within an Id, tbody, tr, title

Using pure javascript

My code

<div id="all-items">
<table>

<tbody>

<tr title="Text 1"></tr>
<tr title="Text 2"></tr>
<tr title="Text 3"></tr>

</tbody>

</table>
</div>


I know with jQuery I can use

$("#all-items table tbody tr").title


will return

"Text 1"


but jQuery isn't working with my front end framework I'm using for some reason. In addition, I want to return all the values of the title attributes on the page within table rows.

Answer

using javascript only...

var rows = document.getElementById('all-items').getElementsByTagName('tr')
var titles = [];

for (var i = 0; i < rows.length; i++) { 
   titles.push(rows[i].getAttribute("title"));
}

console.log(titles);
<div id="all-items">
    <table>

      <tbody>

       <tr title="Text 1"></tr>
       <tr title="Text 2"></tr>
       <tr title="Text 3"></tr>

     </tbody>

    </table>
</div>

Comments