Run through multiple data types using jQuery

Background Info

Hi, im not sure if its possible however Im trying to work out a way that run through a bunch of data-types and change text based on it. I know you can do it by writing every data-type and then editing the related class. However I plan to have loads of data-types and therefore looking for a time saving solution.

So my plan is to have lots of information linked to a certain div, this is so when click it can update a information section based on the data. All of the data-types will have the same data-test-

<div class="box" data-test-1="1.1" data-test-2="1.2" data-test-3="1.3"></div>
<div class="box" data-test-1="2.1" data-test-2="2.2" data-test-3="2.3"></div>
<div class="box" data-test-1="3.1" data-test-2="3.2" data-test-3="3.3"></div>

The question

Is the away I can use jQuery to run through all of the data-test-"" when the box is clicked and then link them to a match ID.

Simplified version -

Answers 1

  • .data() apparently does not recognize digits separated by - as a valid property name.

    You could adjust html to set each data-* as an object containing property names corresponding to id of elements, use $.each() to iterate property names, values and set .html() on matched element that passed .is() condition at if


    <div class="box" 
    <div class="box" 
    <div class="box" 
    <p id="data-test-1">Click on the boxes to change information</p>
    <p id="data-test-2">Infor 2</p>
    <p id="data-test-3">Infor 3</p>
    <p id="data-other-1">Infor 3</p>


    $(".box").click(function() {
      $.each($(this).data(), function(prop, value) {
        $.each(value, function(key, val) {
          var el = $("#data-" + key);
          if ("*")) el.html(val)


Related Articles