Question

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?

Was it helpful?

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/

OTHER TIPS

Here's what I am doing for my dynamic menu items (note: i have no idea what language you're using server side. I use node.js server side and jade for my client side templating).

Note that because you have not asked a precise enough question, I am not exactly sure what you need. You say you want to add data, give us an example of the data you are working with.

Server side:

var user_id = req.session.user.user_id;
// mysql statement to retrieve menu items
mysql.query('select * from menu where user_id = ?',[user_id], function(e, r) {
  var menu;
  // r would be array of objects:
  // [{menu_name: "one", link: "http://foobar.com"},{menu_name:"two",
  // link:"http:otherlink.com"}];
  if (r.length > 0) menu = r;
  else menu = [];
  res.render('menu', {menu: menu});
});

Client side:

html
  body
    section#submenu.navbar
      ul#menu
        - if (menu.length > 0)
           - for (var i = 0; i < menu.length; i++) 
              li
                a(href=#{menu[i].link})= menu[i].menu_name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top