Best practices

  • Use element.getAttribute('data-name') to ensure compatibility with older browsers that may not fully support the dataset API.

  • Prefer element.dataset.name for a more concise and readable approach when working with modern browsers that support HTML5.

  • Use document.querySelector('[data-name="value"]') to select elements based on their data attribute values, which is useful for more complex DOM queries.

  • When dealing with collections of elements, use document.querySelectorAll('[data-name]') and iterate with forEach to handle each element's data attribute efficiently.

// npm install axios jsdom
const axios = require('axios');
const { JSDOM } = require('jsdom');

// Fetch the webpage content
axios.get('https://sandbox.oxylabs.io/products/1')
  .then(response => {
    // Parse the HTML using JSDOM
    const dom = new JSDOM(response.data);
    const document = dom.window.document;
    
    // Select image element
    const element = document.querySelector('.css-pf2yxg');
    // Get data attribute value using getAttribute
    const dataValue = element.getAttribute('data-testid');
    console.log(dataValue);

    // You can achieve the same by using the dataset property for modern browsers
    const dataValue2 = element.dataset.testid;
    console.log(dataValue2);

    // Handling multiple elements with the same data attribute
    const elements = document.querySelectorAll('style');
    elements.forEach(function(el) {
        console.log(el.dataset.emotion);
    });
  })
  .catch(error => console.error('Error:', error));

Common issues

  • Ensure that the data attribute name in JavaScript is in camelCase when using the dataset property, as hyphenated data attributes are converted to camelCase.

  • Validate the existence of the data attribute before accessing it to avoid undefined errors in your JavaScript code.

  • Remember that getAttribute returns the attribute value as a string, so you may need to convert it to another type depending on your needs.

  • For performance optimization, cache your DOM queries when using methods like querySelector or getElementById if you need to access the same elements multiple times.

// Incorrect: Accessing hyphenated data attribute incorrectly
var dataValue = element.dataset.custom-attr; // SyntaxError

// Correct: Convert hyphenated attributes to camelCase
var dataValue = element.dataset.customAttr;


// Incorrect: Directly accessing a data attribute that might not exist
console.log(element.dataset.nonexistent); // Outputs undefined, potentially leading to errors later

// Correct: Check if the attribute exists before using it
if ('nonexistent' in element.dataset) {
    console.log(element.dataset.nonexistent);
} else {
    console.log('Attribute does not exist');
};


// Incorrect: Assuming getAttribute returns a number
var age = element.getAttribute('data-age'); // age is a string, not a number
console.log(age + 5); // Concatenates string with number, e.g., "255"

// Correct: Convert the string to a number when necessary
var age = parseInt(element.getAttribute('data-age'), 10);
console.log(age + 5); // Correctly adds numbers, e.g., 30


// Inefficient: Re-querying the DOM multiple times
for (let i = 0; i < 5; i++) {
    var element = document.getElementById('repeatedId');
    console.log(element.dataset.value);
}

// Efficient: Cache the DOM query
var element = document.getElementById('repeatedId');
for (let i = 0; i < 5; i++) {
    console.log(element.dataset.value);
}

Try Oyxlabs' Proxies & Scraper API

Residential Proxies

Self-Service

Human-like scraping without IP blocking

From

8

Datacenter Proxies

Self-Service

Fast and reliable proxies for cost-efficient scraping

From

1.2

Web scraper API

Self-Service

Public data delivery from a majority of websites

From

49

Useful resources

Web Scraping in JavaScript With Node.js & Puppeteer
adelina avatar

Adelina Kiskyte

2024-10-29

How to Read JSON Files in JavaScript: Tutorial
How to Read JSON Files in JavaScript: Tutorial
vytenis kaubre avatar

Vytenis Kaubrė

2024-07-26

How to Build a Web Scraper?
Iveta Vistorskyte avatar

Iveta Vistorskyte

2021-01-13

Get the latest news from data gathering world

I'm interested