Can I add a custom attribute to an HTML tag?

后端 未结 17 2330
醉话见心
醉话见心 2020-11-22 08:06

Can I add a custom attribute to an HTML tag like the following?


相关标签:
17条回答
  • 2020-11-22 08:42

    Yes, you can do it!

    Having the next HTML tag:

    <tag key="value"/>
    

    We can access their attributes with JavaScript:

    element.getAttribute('key'); // Getter
    element.setAttribute('key', 'value'); // Setter
    

    Element.setAttribute() put the attribute in the HTML tag if not exist. So, you dont need to declare it in the HTML code if you are going to set it with JavaScript.

    key: could be any name you desire for the attribute, while is not already used for the current tag. value: it's always a string containing what you need.

    0 讨论(0)
  • 2020-11-22 08:42

    You can add, but then you have to write a line of JavaScript code too,

    document.createElement('tag');
    

    to make sure everything fall in place. I mean Internet Explorer :)

    0 讨论(0)
  • 2020-11-22 08:42

    You can do something like this to extract the value you want from JavaScript instead of an attribute:

    <a href='#' class='click'>
        <span style='display:none;'>value for JavaScript</span>some text
    </a>
    
    0 讨论(0)
  • 2020-11-22 08:44

    The jQuery data() function allows you to associate arbitrary data with DOM elements. Here's an example.

    0 讨论(0)
  • 2020-11-22 08:47

    Yes, you can use data-* attribute. The data-* attribute is used to store custom data private to the page or application.

    <ul>
        <li data-pageNumber="1"> 1 </li>
        <li data-pageNumber="2"> 2 </li>  
        <li data-pageNumber="3"> 3 </li>  
    </ul
    
    0 讨论(0)
提交回复
热议问题