0

I need to use data attribute in my html like <div id="userlist" data-user="A.A.M"></div> then I need to alert the data-user I used

var userlist = document.getElementById("userlist");

var show = userlist.getAttribute("data-user");
alert(show);

My question is how to handle many data-user in the html like

<div id="userlist" data-user="A.A.M"></div> <div id="userlist2" data-user="A.A.M2"></div> to alert A.A.M and A.A.M2

Thanks in advance and sorry for my bad English.

Ramy Khalid
  • 510
  • 2
  • 4
  • 12
  • You want something that will give you all the elements with that attribute. See http://stackoverflow.com/questions/9496427/can-i-get-elements-by-attribute-selector-when-queryselectorall-is-not-available. Then you will need to loop through them all. – lampwins Jun 01 '14 at 02:41
  • Please can you show me an example as I tried and it didn't work – user3530661 Jun 01 '14 at 03:10

3 Answers3

2

You could select your elements by attribute.

$("div[data-user]").each(function() {
    var user = $(this).data("user");
    alert(user);
});

If you have multiple attributes per element (<div data-user='something' data-another='another'></div>), you can also access those in the same way:

$("div[data-user]").each(function() {
    var user = $(this).data("user");
    var another = $(this).data("another");
    alert(user + ", another: " + another);
});
Mun
  • 14,098
  • 11
  • 59
  • 83
  • 1
    Instead of `$(this).data("user")` try `this.getAttribute("data-user")` or with jQuery `$(this).attr("data-user")`. – Yoann Jun 01 '14 at 05:32
  • @user3530661 Here's a JSFiddle demonstrating this: http://jsfiddle.net/munr/Tk7xL/ – Mun Jun 01 '14 at 20:12
1

you know how to alert 1, alert 2:

alert at the same time:

var data1 = document.getElementById("userlist").getAttribute("data-user");
var data2 =  document.getElementById("userlist2").getAttribute("data-user");

var data = data1 +"\n" +  data2; //"\n" can be other separators you like

alert(data)

if you have many of them, you can use jQuery: add this in your , before any other js code.

 <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

then :

  $("div[id^=userlist]").each(function(){
      alert($(this).attr("data-user"));
    });
Hank X
  • 1,988
  • 2
  • 14
  • 32
0

Calling getElementById on both should work. If you want to iterate you can try to use getElementsByTagName or getElementsByClassName. If you want to select any arbitrary element with the attribute data-user, you can either use querySelectorAll, or check out jQuery, and use $("[data-user]") as a selector.

Does that answer your question?

EyasSH
  • 3,679
  • 22
  • 36
  • I need the javascript to automatically allert 2 time 1 with A.A.M and the other with A.A.M2, Can you show me an example please – user3530661 Jun 01 '14 at 02:55