-2

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.

Details about my goal: I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?

The code:

var deleteLocationID;

$("#deleteLocationBtn").click(function () {
  deleteLocationID = $(document).find(".locationID").val();
  console.log(deleteLocationID);
});

What I have tried so far: Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:

  • deleteLocationID = $(document).find(".locationID").html();
  • deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
  • deleteLocationID = document.getElementsByClassName("locationID").value;

Any help would be much appreciated.

Riyaz Khan
  • 2,765
  • 2
  • 15
  • 29
SamWDev93
  • 1
  • 4

2 Answers2

0

Use the text() method from JQuery, with this you can get the text inside of your element.

Use this way, it may help you:

deleteLocationID = $(document).find(".locationID").text()

Here is example of getting text from class element:

$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
Riyaz Khan
  • 2,765
  • 2
  • 15
  • 29
  • Thanks for this. However after making the change, nothing is still being logged to the console, so I am unsure if it has changed. I have gone through and copy and pasted all of the #id's and .class' used in the code snippet, but still no joy – SamWDev93 Mar 29 '21 at 13:36
  • @SamWDev93, if you could update your HTML tag, we can help you easily. – Riyaz Khan Mar 29 '21 at 13:38
0

It depends on the type of element you are trying to find your value.

for input types you can find the value by .val() in jQuery like:

$(document).find(".locationID").val();

you can grab innerHTML of the element by .html() in jQuery like:

$(".locationID").html();

but if you want to grab innerText of an element you can use .text() in jQuery like:

 $(".locationID").text();
Majid Parvin
  • 4,499
  • 5
  • 29
  • 47