简体   繁体   中英

how to get parent div data-attribute javascript

I have a HTML structure like this :

<div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
   <div class="canvasWrapper" style="width: 816px; height: 1056px;">
      <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
   </div>
   <div class="textLayer" style="width: 816px; height: 1056px;">
        some content
   </div>
</div>

    <div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
       <div class="canvasWrapper" style="width: 816px; height: 1056px;">
          <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
       </div>
       <div class="textLayer" style="width: 816px; height: 1056px;">
            some content
       </div>
    </div>

I want to know that when I click on any textLayer class, I will get data-page-number="x" attribute from its parent .page div .

Only javascript solution required here.

This is basically PDF.js structure.

You could use parentNode.dataset to retrieve data attribute of parent node.

 var textLayer = document.querySelector('.textLayer'); textLayer.addEventListener('click', function(e) { console.log('page number: ' + e.target.parentNode.dataset.pageNumber); console.log('label: ' + e.target.parentNode.dataset.pageLabel); console.log('loaded: ' + e.target.parentNode.dataset.loaded); }); 
 <div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;"> <div class="canvasWrapper" style="width: 816px; height: 1056px;"> <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas> </div> <div class="textLayer" style="width: 816px; height: 1056px;"> some content </div> </div> 

$(".textLayer").on("click",function() {
   $(this).parent().attr("data-page-number");
});

pure js:

var classname = document.getElementsByClassName("textLayer");

var myFunction = function() {
    var attribute = this.parentElement.getAttribute("data-page-number");
};

for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', myFunction, false);
}

// even shorter version

var elems = document.getElementsByClassName("textLayer").forEach(function(element){ 
    element.addEventListener('click', function(){
        var attribute = this.parentElement.getAttribute("data-page-number");
    }, false);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM