Search code examples
htmlmarkup

Add string to html element for javascript parsing?


I have a menu that is created dynamically with javascript.

First it looks for for section elements with a certain attribute eg:

<section something="add"></section>

And adds them to the menu. It also needs to get the title that will appear on each menu item from each element, eg:

<section something="add" something2="Services"></section>

I don't need any help with the js I just want to know how to add the data to the elements and what names give to the attributes. How should I do it?


Solution

  • it would be easy if we set an ID to section

    <section id="sectionUniqueID" data-example="add"></section>
    

    Then manipulate with setAttribute and getAttribute .

    // 'Getting' data-attributes using getAttribute
    var section = document.getElementById('sectionUniqueID');
    var example = section.getAttribute('data-example'); 
    alert(example);
    // 'Setting' data-attributes using setAttribute
    section.setAttribute('data-example2', 'substract');
    var example2 = section.getAttribute('data-example2');
    alert(example2);
    

    Working Demo

    Reference: http://html5doctor.com/html5-custom-data-attributes/