简体   繁体   中英

javascript: how do i get the value of a specific attribute in a nested div

To simplify what I want to achieve, I want to get popular-laptop-deals from data-code="popular-laptop-deals" using a javascript bookmarklet alert.

<div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">

These belong to a nested div where there are other <div> with data-code="". I'm trying to get the function to run through all and get all the other values from data-code="".

I have tried using the following script but it returns "undefined":

 javascript:alert(document.getElementsByName("data-code")[0]);

Appreciate if someone could show or guide me on how i can achieve this.

Thanks in advance.

with querySelector select tag and with getAttribute select attribute

 var attr_code = document.querySelector('div').getAttribute('data-code'); alert(attr_code);
 <div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">

document.getElementsByName("data-code") is an empty NodeList because there are no elements with name s, hence, no element with attribute data-code .

You can change getElementsByName to getElementsByTagName , etc. and then get its attribute value.

Also, data-* attributes can be accessed via the dataset property of an element, eg yourDiv.dataset.code .

 alert(document.getElementsByTagName('div')[0].dataset.code);
 <div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">

With this you can check all div tags on page and add them to array if contain data-code.

var divs = document.getElementsByTagName("div");
var result = [];

for (var i = 0; i < divs.length; i++) {
    if (typeof divs[i].dataset.code !== "undefined") {
        result.push(divs[i].dataset.code);
    }
}

console.log(result)

With Jquery, you can achieve like as below.

Jquery:

 alert($("div").attr("data-code"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="display-table-column scroll-item display-block-xs top-padding-mini-xs tile-highlight category-tile" data-code="popular-laptop-deals" data-testid="tile-highlight">

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