3

I am trying to pass a table variable as a mailto subject.

I am using this script to do for a div ID, but unsure how to to do this for a class - getElementsByClassName doesn't work. How Do I do this?

Button:

<button name="mail_button" onclick="mail_content()">Mail</button> 

Script:

function mail_content() {
    var tableContent = document.getElementById("mailcontent").innerHTML;
    var mBody = "" + tableContent + "";
    document.location.href = "mailto:test@domain.com?subject=Titel&body=" + mBody;  
}

Element I wish to fect the varable from:

<td class="mailcontent">N7P47AA</td>
Haseeb Ibrar
  • 337
  • 5
  • 18
Jerry
  • 1,069
  • 2
  • 13
  • 31
  • 1
    Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Sebastian Simon Aug 30 '17 at 11:13

2 Answers2

2

You have to use the index.Class is not unique like the id.

document.getElementsByClassName("mailcontent")[0].innerHTML

1) Select it via an ID that is unique.

2) Select it via a Class and index combination.

Here is the Docs for it: https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName

function mail_content() {
  var tableContent = document.getElementsByClassName("mailcontent")[0].innerHTML;
  var mBody = "" + tableContent + "";
  document.location.href = "mailto:test@domain.com?subject=Titel&body=" + mBody;
}

mail_content();
<table>
  <td class="mailcontent">N7P47AA</td>
</table>
Cosmin_Victor
  • 154
  • 1
  • 13
1

You are doing document.getElementById("mailcontent"), but the element you are looking for has no ID attribute. Currently your element has a class attribute of mailcontent, so you have 2 options:

  1. Add an ID attribute to your element and give it an id of mailcontent
  2. Change document.getElementById to:

    document.getElementsByClassName("mailcontent")[0].innerHTML

    Remember, document.getElementsByClass name returns an array, rather than a single item, hence the addition of the [0] so you can get the first item in the array

Steven Brookes
  • 834
  • 6
  • 27