Neeraj Walia
Neeraj Walia

Reputation: 228

How to Add html element in data attribute

I want to add whole html element to data attribute so that on click I can set it to localstorage and can use it on next pages as well instead of doing the same stuff again on next page ...

Here is what I was doing...

Checking if img_src has a value or not
if false than set a div with letter X and some styling
if true set img tag with src and some width and height

      var img_src="userpic.png"; //this value comes from db
      if(img_src=="" || img_src==null){
        var po_img = '<div class="class-groupPic bg-1">X</div>';
      }
      else{
        var po_img = '<img src="'+element.student.photo+'" width="34" height="34"/>';
      }

      <div class="col" data-img="'+po_img+'" data-religion="Hindu" data-category="OBC"></div>

Jquery on click

        $(".col").on('click',function(){
           window.localStorage.setItem('img',$(this).data('img'));
           window.localStorage.setItem('religion',$(this).data('religion'));
           window.localStorage.setItem('category',$(this).data('category'));            
        });

But this adding html inside data attirbute results
enter image description here

This above image is my html page result

Upvotes: 2

Views: 2802

Answers (1)

Andrew L
Andrew L

Reputation: 5486

One solution that works is using jQuerys constructor to create the elements and then using those elements to set the data- attributes to store it. This example works and seems to do what you want.

var img_src = "userpic.png"; //this value comes from db
var element = {
  student: {
    photo: "myImage.com"
  }
}; // for this example only

var $po_img;
if (img_src == "" || img_src == null) {
  $po_img = $('<div>', { class: "class-groupPic bg-1"});
  $po_img.text("X");
} else {
  $po_img = $('<img/>', {src: element.student.photo, width: 34, height: 34});
}

var $myDiv = $('<div/>', { id: "myDiv", class: "col"});
$myDiv.text("I am the div");
$myDiv.attr("data-img", $po_img[0].outerHTML);
$myDiv.attr("data-religion", "Hindu");
$myDiv.attr("data-category", "OBC");

// add the div to the DOM
document.write($myDiv[0].outerHTML);

// Retrieve the img HTML from the div's data attribute
var theImage = $("#myDiv").attr("data-img");
console.log(theImage);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions