i would like to take the value of an li in alert box using javascript.(i.e If i click on PHP it should alert php in alert box). But its showing undefined. Please anyone help on this.
My code is
<script type="text/javascript">
function lang1()
{
var a = document.getElementsByTagName("li").value;
alert(a);
}
</script>
<form>
<ul id="language" onclick="lang1();">
<li>PHP</li>
<li>ASP</li>
<li>JAVA</li>
<li>CQ5</li>
</ul>
</form>
ul stands for unordered list. li stands for list item. They are the HTML tags for "bulleted" lists as opposed to "numbered" lists (which are specified by ol for ordered list).
Answer: yes it does, but with: ol or menu, that's all!
Firstly, there is no value attribute available on an li element, and adding non-standard attributes will mean that your page is invalid.
getElementsByTagName
returns a NodeList
, i.e. a list of elements. But even of you accessed one element of the list, li
elements don't have a value
property (only form control elements have this property).
You can use .innerHTML
or .textContent
/.innterText
to access the content of HTML elements.
Now, you want to get the content of the li
element that was clicked. Since you bound the event handler to the ul
element, this
will always refer to the ul
element inside the event handler.
But you can get the element which triggered the event by accessing the target
(or srcElement
(IE)) property of the event object.
W3C compatible browsers pass the event object as argument to the event handler. In older IE versions the event object is available as global variable, window.event
. Since you are using inline event handlers there is no difference for you in this case.
<script type="text/javascript">
function lang1(event) {
var target = event.target || event.srcElement;
alert(event.target.innerHTML);
}
</script>
<form>
<ul id="language" onclick="lang1(event);">
<li>PHP</li>
<li>ASP</li>
<li>JAVA</li>
<li>CQ5</li>
</ul>
</form>
DEMO
I recommend to read the excellent articles about event handling on quirksmode.org. They describe the different ways of binding event handlers (inline ve, which properties the event object has and the differences between browsers.
Note: Inline event handlers are OK for toy examples, but as soon as your going to do some serious development, use other ways to bind event handlers.
document.getElementsByTagName() return a node list not an element.
You need iterract this node list to get the value of each element Example
var elementsLI = document.getElementsByTagName('li')
var length = document.getElementsByTagName('li').length;
for(var i = 0; i <= length ; ++i){
alert(elementsLI[i].value);
}
Hope it helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With