How to read array of values from browser DOM using jQuery, or in Node.js using Cheerio

By: (plus.google.com) +David Herron; Date: March 12, 2019

Tags: JavaScript » jQuery

Typically with jQuery or Cheerio we read or write strings and numbers to/from the DOM, but what if we must use objects or arrays of data? The jQuery documentation mentions data-* attributes, but the documentation is not entirely clear how to use this for reading/writing objects or arrays to/from the DOM.

jQuery is a very useful tool to simplify DOM manipulation in browser-side JavaScript, and is useful on the server-side in Node.js using the Cheerio library. The following examples will work in either environment.

The other day I needed to pass an array of strings into a custom HTML element I was defining in AkashaCMS. AkashaCMS uses server-side jQuery-like manipulation implemented with the Cheerio library for modifying HTML files before publishing them to the server. What I thought would work didn't work, and I was about to give up. Instead I went to Codepen and played around using browser-side jQuery to figure it out.

Everything shown below has been verified in Node.js using Cheerio.

Problem statement: How to pass an array of data values using a data-foo= attribute in an HTML element, such that jQuery recognizes it as an array, and passes a JavaScript Array object to the code.

I tried a number of bad ideas, that I don't remember, so I'll cut to the chase and show the syntax that worked.

<div id="foo" 
    data-products='[ "camco-14-50-extcord", "conntek-14-50-extcord", "ge-14-50-extcord", "petra-14-50-extcord", "coleman-14-50-extcord", "nucord-14-50-extcord", "utilitech-14-50-extcord" ]'>
</div>

In JavaScript/jQuery this is read as so:

<script>
let d = $("#foo").data('products');
console.log(d);
</script>

Generally speaking the .data method in jQuery reads/writes data-* attributes. The data- part of the name is stripped off, or added, as appropriate, and therefore what the coder sees as a products attribute is actually data-products in the DOM.

The key here is using single-quote for the outer level string delimiter, and double-quote to delimit strings within the string. My initial attempt had these reversed, double-quote for the outer delimiter, and single-quote for inner delimiters. That arrangement gave a ton of errors, and using quotes as shown above worked.

To prove this works, I'll embed the example as live code. First we'll show the modifications required to show this visually:

<div id="foo" 
    data-products='[ "camco-14-50-extcord", "conntek-14-50-extcord", "ge-14-50-extcord", "petra-14-50-extcord", "coleman-14-50-extcord", "nucord-14-50-extcord", "utilitech-14-50-extcord" ]'>
</div>

<ol id="target">
</ol>

<script>
document.addEventListener("DOMContentLoaded", function(){
    let d = $("#foo").data('products');
    console.log(d);
    for (let item of d) {
        $("#target").append('<li>'+ item +'</li>');
    }
});

</script>

And then we have the live code.

To see the console.log output you'll need to open the browser console log.

JavaScript array output in the Chrome developers console

Parsing an array is all well and good, what about an object? The array notation here is the same as JSON, and it appears from the jQuery documentation that a JSON object notation will work, so here goes:

<div id="foo2"
    data-products='{ "prod1": "camco-14-50-extcord", "prod2": "conntek-14-50-extcord", "others": [ "ge-14-50-extcord", "petra-14-50-extcord", "coleman-14-50-extcord", "nucord-14-50-extcord", "utilitech-14-50-extcord" ]}'>
</div>

<pre id="target2"></pre>

<script>
document.addEventListener("DOMContentLoaded", function(){
    let d = $("#foo2").data('products');
    console.log(d);
    $("target2").text(JSON.stringify(d));
});
</script>

A few simple modifications to the example. The data is restructured to make an object with three elements, one of which is an array. Instead of interpolating the data item, we'll just stringify it and plop it into a target.



Again, open the console log to see the message.

JavaScript object output in the Chrome developers console
« Greetings, introducing myself Sen. Warren seeking to break up Apple, after calling for Facebook/Amazon/et/al breakup »
2016 Election 2018 Elections Acer C720 Ad block Affiliate marketing Air Filters Air Quality Air Quality Monitoring AkashaCMS Amazon Amazon Kindle Amazon Web Services America Amiga and Jon Pertwee Android Anti-Fascism AntiVirus Software Apple Apple Flexgate Apple Hardware History Apple Hardware Mistakes Apple iPhone Apple iPhone Hardware April 1st Arduino ARM Compilation Artificial Intelligence Astronomy Astrophotography Asynchronous Programming Authoritarianism Automated Social Posting AWS DynamoDB AWS Lambda Ayo.JS Bells Law Big Brother Big Data Big Finish Big Science Bitcoin Mining Black Holes Blade Runner Blockchain Blogger Blogging Books Botnets Cassette Tapes Cellphones China China Manufacturing Christopher Eccleston Chrome Chrome Apps Chromebook Chromebox ChromeOS CIA CitiCards Citizen Journalism Civil Liberties Climate Change Clinton Cluster Computing Command Line Tools Comment Systems Computer Accessories Computer Hardware Computer Repair Computers Conservatives Cross Compilation Crouton Cryptocurrency Curiosity Rover Currencies Cyber Security Cybermen Cybersecurity Daleks Darth Vader Data backup Data Formats Data Storage Database Database Backup Databases David Tenant DDoS Botnet Department of Defense Department of Justice Detect Adblocker Developers Editors Digital audio Digital Nomad Digital Photography Direct Attach Storage Diskless Booting Disqus DIY DIY Repair DNP3 Do it yourself Docker Docker MAMP Docker Swarm Doctor Who Doctor Who Paradox Doctor Who Review Drobo Drupal Drupal Themes DuckDuckGo DVD E-Books E-Readers Early Computers eGPU Election Hacks Electric Bicycles Electric Vehicles Electron Eliminating Jobs for Human Emdebian Encabulators Energy Efficiency Enterprise Node EPUB ESP8266 Ethical Curation Eurovision Event Driven Asynchronous Express Face Recognition Facebook Fake Advertising Fake News Fedora VirtualBox Fifth Doctor File transfer without iTunes FireFly Flash Flickr Fraud Freedom of Speech Front-end Development G Suite Gallifrey Gig Economy git Github GitKraken Gitlab GMAIL Google Google Adsense Google Chrome Google Gnome Google+ Government Spying Great Britain Green Transportation Hate Speech Heat Loss Hibernate High Technology Hoax Science Home Automation HTTP Security HTTPS Human ID I2C Protocol Image Analysis Image Conversion Image Processing ImageMagick In-memory Computing Incognito Mode InfluxDB Infrared Thermometers Insulation Internet Internet Advertising Internet Law Internet of Things Internet Policy Internet Privacy iOS iOS Devices iPad iPhone iPhone hacking Iron Man iShowU Audio Capture iTunes Janet Fielding Java JavaFX JavaScript JavaScript Injection JDBC John Simms Journalism Joyent jQuery Kaspersky Labs Kext Kindle Kindle Marketplace Large Hadron Collider Lets Encrypt LibreOffice Linux Linux Hints Linux Single Board Computers Logging Mac Mini Mac OS Mac OS X Mac Pro MacBook Pro Machine Learning Machine Readable ID Macintosh macOS macOS High Sierra macOS Kext MacOS X setup Make Money Online Make Money with Gigs March For Our Lives MariaDB Mars Mass Violence Matt Lucas MEADS Anti-Missile Mercurial MERN Stack Michele Gomez Micro Apartments Microsoft Military AI Military Hardware Minification Minimized CSS Minimized HTML Minimized JavaScript Missy Mobile Applications Mobile Computers MODBUS Mondas Monetary System MongoDB Mongoose Monty Python MQTT Music Player Music Streaming MySQL NanoPi Nardole NASA Net Neutrality Network Attached Storage Node Web Development Node.js Node.js Database Node.js Performance Node.js Testing Node.JS Web Development Node.x North Korea npm NSA NVIDIA NY Times Online advertising Online Community Online Fraud Online Journalism Online News Online Photography Online Video Open Media Vault Open Source Open Source and Patents Open Source Governance Open Source Licenses Open Source Software OpenAPI OpenJDK OpenVPN Palmtop PDA Patrick Troughton PayPal Paywalls Personal Flight Peter Capaldi Peter Davison Phishing Photography PHP Plex Plex Media Server Political Protest Politics Postal Service Power Control President Trump Privacy Private E-mail server Production use Public Violence Raspberry Pi Raspberry Pi 3 Raspberry Pi Zero ReactJS Recaptcha Recycling Refurbished Computers Remote Desktop Removable Storage Renewable Energy Republicans Retro Computing Retro-Technology Reviews RFID Rich Internet Applications Right to Repair River Song Robotics Robots Rocket Ships RSS News Readers rsync Russia Russia Troll Factory Russian Hacking Rust SCADA Scheme Science Fiction SD Cards Search Engine Ranking Search Engines Season 1 Season 10 Season 11 Security Security Cameras Server-side JavaScript Serverless Framework Servers Shell Scripts Silence Simsimi Skype SmugMug Social Media Social Media Networks Social Media Warfare Social Network Management Social Networks Software Development Software Patents Space Flight Space Ship Reuse Space Ships SpaceX Spear Phishing Spring Spring Boot Spy Satellites SQLite3 SSD Drives SSD upgrade SSH SSH Key SSL Stand For Truth Strange Parts Swagger Synchronizing Files Tegan Jovanka Telescopes Terrorism The Cybermen The Daleks The Master Time-Series Database Tom Baker Torchwood Total Information Awareness Trump Trump Administration Trump Campaign Twitter Ubuntu Udemy UDOO US Department of Defense Video editing Virtual Private Networks VirtualBox VLC VNC VOIP Vue.js Walmart Weapons Systems Web Applications Web Developer Resources Web Development Web Development Tools Web Marketing Webpack Website Advertising Website Business Models Weeping Angels WhatsApp William Hartnell Window Insulation Windows Windows Alternatives Wordpress World Wide Web Yahoo YouTube YouTube Adpocalypse YouTube Monetization