Search code examples
javascriptbookmarklet

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.


Solution

  • document.getElementsByName("data-code") is an empty NodeList because there are no elements with names, 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, e.g. 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">