Reputation: 1014
I have a html page containing something like:
<div data-variableid2="1234"> </div>
How can I get the 1234 value of an element (without jQuery) and show it with alert()
?
Upvotes: 0
Views: 4389
Reputation: 9131
First you should give your DIV an id.
<div id="myid" data-variableid2="1234"> </div>
Then you could display the attributes data using
var MyDiv1 = document.getElementById('myid');
alert(MyDiv1.getAttribute('data-variableid2'));
Just test it here: http://jsfiddle.net/5C4NA/
But if you are not allowed to change the HTML of your pages, you should stick to something like
document.getElementsByTagName("div")[0]
but the index (here 0
) does vary with the position of the div within the HTML page.
Edit 1:
With a loop you are able to scan through all DIVs and choose the one with an attribute data-variableid2
: http://jsfiddle.net/5C4NA/1/ This looks like:
var elm = document.getElementsByTagName("div");
for (i=0;i<elm.length;i++) {
if (elm[i].getAttribute('data-variableid2')!=null) {
alert(elm[i].getAttribute('data-variableid2'));
}
}
Upvotes: 1
Reputation: 9788
Assuming that you dont use jQuery, (because it wasn't tagged):
HTML: (I used id for div element to simplify things):
<div id="example" data-variableid2="1234"></div>
JavaScript:
// capture element
var example = document.getElementById('example');
// capture data variable value
var dataVar = example.getAttribute('data-variableid2');
// show it with alert
alert(dataVar);
Here is the example: js fiddle
Edit:
In case you cant use id or class for an element you can then capture it with this (0 is the number of the element):
var example = document.getElementsByTagName("div")[0];
If (and most likely) its not the only div at the page, you can try querySelectorAll
Like this:
// capture element - references to 0 which is the first matched element
// because this will select group of elements with data-variableid2
var example = document.querySelectorAll("[data-variableid2]")[0];
Here is the example with that: js fiddle
Upvotes: 2
Reputation: 1619
var elm = document.getElementsByTagName("div")[0]; //get element
alert(elm.getAttribute("data-variableid2")); //alert attribute
Note: you should add an id to the div and get the element by id (for performance).
This is done by plain Javascript, no jQuery required.
Upvotes: 3
Reputation: 11
You can do this like that with jQuery
<div data-variableid2="1234"> </div>
<script>
var data = $('div').attr('data-variableid2');
alert(data);
</script>
Upvotes: 0