skip to Main Content

Is there any way to add multiple data-***** attributes and class inside a html file using Javascript. I know how to add a tag inside html file using javascript, and as well as add data-***** attributes. But theres two fact. Is there any shortest way to add it ? and my one is not working.

This is my way to add class and tag using js.

<body>
<script>
let add_element = () => {
const template = document.createElement('div');
template.classList.add("mytag");    
document.body.appendChild(template);
}
add_element();
</script>
</body>

This is my code. I want to add this tag with all attributes inside HTML file using Javascript. How can I do it ?

<span id='an-id' data-page='active' data-page-text='This is page text.' data-print='active' data-print-text='This is print text'></span>

How I can add this tag inside HTML file using javascript with all attributes ?

3

Answers


  1. Use element.dataset property. For details.

    Example:

    let add_element = () => {
      const template = document.createElement('span');
      template.classList.add("mytag");
      template.dataset.page = 'active';
      template.dataset.pagetext = 'This is page text.';
      template.dataset.print = 'active';
      template.dataset.printtext = 'This is print text';
      template.innerHTML = "span with data attribute.";
    
      document.body.appendChild(template);
    }
    add_element();

    Note: Follow proper naming convention. Don’t use dash on data attribute name.

    Wrong: data-page-text ,

    Correct: data-pagetext

    Login or Signup to reply.
  2. same as @Mb.Ibrahim said however w3c standards are usually quite open and you can use - in your attr name like data-page-text

    note: there’s no w3c standard that says you can’t use - in your data- name like he says

    // <span id='an-id' data-page='active' data-page-text='This is page text.' data-print='active' data-print-text='This is print text'></span>
    const span = document.createElement("span")
    
    span.setAttribute('id', 'an-id') // or span.id = 'an-id'
    
    span.dataset.page = 'active' // data-page
    span.dataset.pageText = 'This is page text.' // data-page-text
    span.dataset.print = 'active' // data-print
    span.dataset.printText = 'This is print text' // data-print-text
    
    document.body.appendChild(span)
    

    or you can also use setAttribute or object to set properties faster.

    if you use jquery this is even easier:

    $('body').append("<span id='an-id' data-page='active' data-page-text='This is page text.' data-print='active' data-print-text='This is print text'></span>")
    

    or

    $("<span id='an-id' data-page='active' data-page-text='This is page text.' data-print='active' data-print-text='This is print text'></span>").appendTo('body')
    
    Login or Signup to reply.
  3. You can create some cool reusable DOM helper functions to either,
    create a new element

    elNew("SPAN", { /* properties */ })
    

    add attributes

    attr(myElement, { /* attributes */ })
    

    get an element

    el("#someId")
    

    Etc.
    Here’s an example that creates a SPAN, set some initial properties, adds attributes, and insert it into the Document as child of any Element:

    // DOM utility functions
    const el = (sel, par) => (par || document).querySelector(sel);
    const elNew = (tag, props) => Object.assign(document.createElement(tag), props);
    const attr = (el, attrs) => Object.entries(attrs).forEach(([k, v]) => el.setAttribute(k, v));
    
    // Task: create element and append to document:
    
    const elSpan = elNew("span", {
      // Add some properties
      id: "some-id",
      className: "active foo bar",
      textContent: "Click me",
      title: "I like titles!",
      style: "color: blue;",
      onclick() {
        this.textContent = "Clicked!"
      }
    });
    
    // Add attributes:
    attr(elSpan, {
      "data-page": "active",
      "data-pageText": "This is page text.",
      "data-print": "active",
      "data-printText": "This is print text",
      "aria-label": "Some accessibility label",
    });
    
    // Insert it wherever you want:
    el("body").append(elSpan);
    
    // Test:
    console.log(elSpan.outerHTML);

    Some other helper functions you could create:

    const els = (sel, par) => (par || document).querySelectorAll(sel);
    const css = (el, styles) => typeof styles === "object" ? Object.assign(el.style, styles) : el.style.cssText = styles;
    

    …you got the point. Helps really into saving keystrokes while maintaining logic and readability.


    To specifically create a helper function for the data-* attributes only, instead of using .setAttribute() you could go for Element.dataset:

    // DOM utility functions
    const el = (sel, par) => (par || document).querySelector(sel);
    const elNew = (tag, props) => Object.assign(document.createElement(tag), props);
    const data = (el, data) => Object.entries(data).forEach(([k, v]) => el.dataset[k] = v);
    
    // Task: create element and append it to the document:
    
    const elSpan = elNew("span", { textContent: "I'm a span!"});
    
    // Add data-* attributes:
    data(elSpan, {
      "page": "active",
      "pageText": "This is page text.",
      "print": "active",
      "printText": "This is print text",
    });
    
    // Insert it wherever you want:
    el("body").append(elSpan);
    
    // Test:
    console.log(elSpan.outerHTML);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search