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()
?
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()
?
- is there a class or id or anything on the div? and are you using jQuery or straight javascript? – pathfinder Commented Mar 27, 2014 at 23:18
4 Answers
Reset to default 3var 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.
getAttribute() Reference
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
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/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/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'));
}
}
You can do this like that with jQuery
<div data-variableid2="1234"> </div>
<script>
var data = $('div').attr('data-variableid2');
alert(data);
</script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745236022a4617896.html
评论列表(0条)