How to set single attribute on dynamically created element

后端 未结 2 1365
陌清茗
陌清茗 2021-01-27 12:02

I have to dynamically create an Anchor tag that I am adding a Foundation aspect to. One of the elements is called \"data-tooltip\" that Foundation uses.

If I\'m trying

2条回答
  •  不要未来只要你来
    2021-01-27 12:27

    If you want the following element this way exactly and existing on your page as an element in the DOM:

    FOO
    

        var artworkColumn = document.createElement("a");
        artworkColumn.setAttribute("aria-haspopup", "true");
        artworkColumn.setAttribute("data-tooltip", "");
        artworkColumn.innerHTML = "FOO";
        document.body.appendChild(artworkColumn);

    If your'e looking for functional results refer to the following portion of this answer:


    After creating a node/element you must append it to DOM.

    Also, I think when you are dealing with a boolean value, you actually don't include the quotes (true instead of "true", because anything in quotes is a String type and a Boolean type is not a String).

    You can use setAttribute() to create or dataset to set a data-* attribute, remember to change the name when invoking it with dataset (ex. data-tooltip would be tooltip in your JS code, using dataset.) I recommend using setAttribute()

    Here's an article that'll set you straight on the data-*

    // Using setAttribute()
    var artworkColumn = document.createElement("a");
    artworkColumn.setAttribute("aria-haspopup", true);
    artworkColumn.setAttribute("data-tooltip", "");
    artworkColumn.setAttribute("href", "http://cdn.playbuzz.com/cdn/b19cffffd2-1b79-4679-b6d3-1bf8d7235b89/93794aec-3f17-47a4-8801-a2716a9c4598_560_420.jpg");
    artworkColumn.innerHTML = "Starry Night, Vincent Van Gogh";
    document.body.appendChild(artworkColumn);
    
    // Using dataset
    var art = document.getElementById('artwork1');
    var tip = art.dataset.tooltip;
    console.log('tip: '+tip);
    
    // Use DevTools in the browser to test both methods.  
    // To see the anchor object, artworkColumn: 
    
       /* F12 then find the Element tab to see the new link,
          there's also an empty "Link" under the image. */
    
    // To test to see if the data-tooltip was created:
    
       /* F12 then find the Console tab,
          you'll see the log: 'tip: circa. 1889' */
    a { color: red; text-decoration: none; font-size: 42px;}
    a:hover {color: blue; text-decoration: underline; cursor: pointer; }
    a:before { content: 'Link: ';}

提交回复
热议问题