0

So I have the following code

var email = row.cells[2];
console.log(email);

and that returns <td>[email protected]</td>as an object I think however I need that value as a string in order to remove the <td></td> I some websites says that I can use JSON.stringify but when i do it like that it returns {} anybody knows why?.

4
  • 4
    Because it's not a JavaScript object - it's a DOM node. Do email.textContent instead. Commented Nov 8, 2016 at 21:16
  • everything in javascript is an object, including strings and dom nodes. Commented Nov 8, 2016 at 21:17
  • @Iwrestledabearonce. aside from being untrue in general (see: primitives) I was just explaining why JSON.stringify doesn't work. Commented Nov 8, 2016 at 21:21
  • @Iwrestledabearonce. doesnt necessarily mean that It can be stringified by JSON methods. Commented Nov 8, 2016 at 21:22

2 Answers 2

3

The value that is returned is not just a normal JavaScript object, it's a special one. It is a DOM node, or more specifically a DOM element. It is the way the page is represented in JS.

Because of this, JSON.stringify() returns {}. Luckily, DOM elements have their own way of getting contents. To get the text content of a DOM element, use .textContent. In this case, it would be

var DOM_Element = row.cells[2];
var email = DOM_Element.textContent
console.log(email);

Consider also innerHTML

var email = row.cells[2].innerHTML
console.log(email);

Credit to @vlaz's comment.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so did I get something wrong? I thought this was the right procedure: when someone answers the question in the comments, create a community wiki to say what they said, so the answer can be accepted. Should I have waited longer, or is there some facts I got wrong?
Not sure what the downvote was about, really. If it is about the comment - I'm perfectly happy with people using it. It's why I left it there. Just couldn't be bothered to post an actual answer.
0

try

var email = row.cells[2].textContent;

2 Comments

remove the stringify, it's not JSON, doesn't need to be stringified.
Yeah OP caught my attention with that stringify, see edited answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.