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
Use
element.dataset
property. For details.Example:
Note: Follow proper naming convention. Don’t use dash on data attribute name.
Wrong:
data-page-text
,Correct:
data-pagetext
same as @Mb.Ibrahim said however w3c standards are usually quite open and you can use
-
in your attr name likedata-page-text
or you can also use
setAttribute
or object to set properties faster.if you use jquery this is even easier:
or
You can create some cool reusable DOM helper functions to either,
create a new element
add attributes
get an element
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:Some other helper functions you could create:
…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: