Adding a linebreak between elements HTML code breaks "parentnode" based javascript function -


this question has answer here:

i have an html form simple javascript function meant send user different link based on option selected.

<form> <select name="deliverytype">     <option value="123">item 1</option>     <option value="456">item 2</option>     <option value="789">item 3</option> </select> <p><a href="javascript:void(0);" onclick="javascript:addtocart(this);">submit</a> <script>     function addtocart(t) {     var dt = t.parentnode.parentnode.childnodes[1].value;     alert(dt);     // location.href = "http://linkprefix.com/?variable=" + dt; }</script> </form> 

it works expected. variable dt returns value of selected option.

however, if there no line break between <form> , <select>, dt returns undefined. if change childnodes[1] childnodes[0] works again. don't know why happen. thought parentnode , childnode based on html elements , text within them, not line breaks between elements. if had guess, line break being counted text node, makes no sense me. what's happening? there better way this?

that's because in html, whitespace inside elements considered text, , text considered nodes (see w3schools). adding line break, adding node, why <select> node accessible through childnodes[1]. if there no line breaks, <select> node accessible through childnodes[0].


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -