0

I have in my this.nameHtml a DOM object with value:

<span class='test-name'>333</span>

I want to access the innerHTML i.e. 333

basically I am creating a checkbox element and want to assign the 333 value from DOM object in name attribute as follow:

checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.name = this.nameHtml;   // Here i want to store 333 
checkBox.className = "TriageCheckBox";

Please suggest a way.

Om Sao
  • 7,064
  • 2
  • 47
  • 61
  • What are you trying? A checkbox can only hold the value checked or unchecked. It is not meant to store strings or numbers. – Benedikt Sep 22 '14 at 08:16
  • Sorry Benedikt, I meant, checkBox.name – Om Sao Sep 22 '14 at 08:18
  • 1
    Keep in mind that you may run in trouble, when the name field begins with a number. http://stackoverflow.com/questions/2469355/input-field-name-starts-with-a-number – Benedikt Sep 22 '14 at 08:20

2 Answers2

1

Try using innerHTML property :

checkBox.name = document.getElementByClassName("test-name")[0].innerHTML;

NB : document.getElementByClassName("test-name")[0] get first element with test-name class, be sure to adjust index if multiple ones.

Hotted24
  • 502
  • 3
  • 8
  • Hi Hotted24, unfortunately I can't use your suggestion, there will be dynamically generated checkboxes hence keeping track of index number will be difficult – Om Sao Sep 22 '14 at 08:25
  • Then give them IDs and use getElementById("") ;) I believe you can use a simple global var like an index to make it unique =) BTW, instead of document.getEle, if you have access to the object from the inside, it's simpler : checkBox.name = this.innerHTML; – Hotted24 Sep 22 '14 at 08:40
  • Thanks Hotted24. Yes, did in your way ! – Om Sao Sep 22 '14 at 09:12
0
checkBox.name = this.nameHtml.innerText;

Beware of innerHtml! This may print unwanted html code and destroy your site structure! Difference between innerText and innerHTML in javascript

Regards, Benedikt

Community
  • 1
  • 1
Benedikt
  • 954
  • 3
  • 14
  • 25