Use .text() to display in anchor tag

Is it okay to use .text() which doing the following?


var data = [
  {
    "id": 3,
    "name": "LIST#3",
    "description": "Updated  description test",
    "comment": "Updated  description test",
    "locationId": 23,
    "capacity": 56,
    "isFull": false,
    "entryDate": null,
    "endDate": null
  }
];

console.log(data);
console.log(data[0].name);

$("#test").text(data[0].name);

here is HTML:

<a id="test" href="list.html?id=3"></a>

This does print LIST#3 with hyperlink but I was reading the documentation here : https://api.jquery.com/text/

which says .text() doesn’t accept any arguments. So am I doing something wrong here?

Jquery documentation is a little bit confusing. On the top there is the manual for the text() function as a getter function, which of course is accepting no arguments.
But when you scroll down the page, you will find the manual for the setter function text(text) which is what you are using.

At least I would not use jquery any more and use the vanilla JavaScript function textContent instead.

1 Like

most jquery functions are overloaded - they do different things depending on how many parameters you give it. The usual format is that the base function gets the value, and the function with an additional parameter sets the value.

.val() gets the value; .val("something") sets the value;
,prop("src") gets the src attribute’s value; .prop("src","aurlhere") sets the src attribute’s value;

1 Like

Can I do something to display a default text over here, like this:

<a id="test" href="list.html?id=3">N/A</a>

And when I plan to display the value using $("#test").text(data[0].name);, it will appear over there? I want to display N/A without hyperlink and then replace it with the actual value which I think could be possible with .replaceWith() jQuery function.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.