Home > Blockchain >  Create a new property and get element id?
Create a new property and get element id?

Time:03-20

I want to create a new property and get id for elements (demo1, demo2, demo3).

id: this.id = How do I get the id from the elements here?

Element.prototype.myData = {
  id: '1', 
  name: 'Caesar',
  title: 'Imperator'
  var att = "{id:" id ";name:" name ";title:" title "}";
  document.getElementById(this.id).setAttribute("myAtt", att); // get id of element
  
};

alert(document.getElementById("demo1").myData.id = "129"); // alert 129

alert(document.getElementById("demo2").myData.id = "65"); // alert 65
alert(document.getElementById("demo2").myData.name = "Aleksandar"); // alert Aleksandar

alert(document.getElementById("demo3").myData.title); // alert Imperator
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>

CodePudding user response:

class CustomDiv extends HTMLDivElement {
    myData = {
       id: '',
       name: 'Caesar',
       title: 'Imperator'
    };
    constructor() {
        super();
    }

    connectedCallback() {
        this.myData.id = this.getAttribute('id');
    }
}

customElements.define('custom-div',CustomDiv , {extends: 'div'});


alert(document.getElementById("demo1").myData.id); // alert demo1

alert(document.getElementById("demo2").myData.name); // alert Cesar

alert(document.getElementById("demo3").myData.title); // alert Imperator
<div is="custom-div" id="demo1"></div>
<div is="custom-div" id="demo2"></div>
<div is="custom-div" id="demo3"></div>

  • Related