Search code examples
javascriptdatasetbookmarkletselectors-api

How to find innerText or textContent of a specific dataset (data-*) using queryselector javascript?


I don't know javascript, I am learning as I attempt a project.

I am having trouble reading textContent from a specific dataset attribute.

e.g. <span data-field="member.firstName">JOHN</span>
I need to read 'member.firstname', which should return "JOHN"

I am creating bookmarklets which also seems to be limiting my use. I've found answers involving jQuery but I... a. Don't understand the syntax. b. Don't even know if I can use it in bookmarklets.

Using queryselector, the only results I have gotten other than NULL or Undefined involved using nth-child[] in my selector.

javascript:(function(){console.log(document.querySelector('#calldetails-tab-summary > div > div.d3ui-col-6.calldetails-tab-content-col1 > fieldset:nth-child(1) > div.d3ui-tab-content-widget-content-readonly > div:nth-child(1) > span:nth- child(2) > span'));})();

but the nodes are not constant in the container I am querying and this code only returns <span data-field="member.firstName">JOHN</span>

this snip of the html should be suitable as stand alone tester.

<div id="calldetails-tab-summary" class="d3ui-container ui-tabs-panel ui- 
widget-content ui-corner-bottom" data-tabkey="E1-SUMMARY">
<div class="d3ui-row">
<div class="d3ui-col-6 calldetails-tab-content-col1"><fieldset data- 
groupkey="E1-SUMMARY-MEMBER-SUMMARY" data-editable="true" class="d3ui-tab- 
content-widget " title="Member Summary">
<div class="d3ui-tab-content-widget-header">
<div class="d3ui-tab-content-widget-header-text ">Member Summary</div>
</div>
<div class="d3ui-tab-content-widget-content-readonly">
<div data-audit="" class="" data-fieldkey="memberName" title="Name">
<label>Name</label>
<span class="">
<span data-field="member.firstName">JOHN</span>
</span>
<span class="">
<span data-field="member.lastName">DOE</span>
</span>

Solution

  • Try this:

    alert(document.querySelectorAll("[data-field='member.firstName']")[0].innerText);
    

    Link to fiddle (ES6): https://jsfiddle.net/hcrov42e/