0

How would you access the value of an em tag in javascript?

This is the element I'm trying to access: <em id='tag_IS_System_Agent'></em>

which displays: John Smith

I'm trying to access it via javascript:

document.getElementById("emailFrame").src 
= "http://www.website.org/mail.php?cid="
  +IS_ATTR_ID.value
  +"&name="+document.write("<em id=\"tag_IS_System_Agent\">&nbsp;<\/em>")
  +"&em="+email;`

Any idea? I know that document.write("<em id=\"tag_IS_System_Agent\">&nbsp;<\/em>") is wrong and I'm stumped and not sure what to do.

2
  • 5
    document.getElementById("tag_IS_System_Agent");
    – crush
    Sep 13, 2013 at 0:31
  • You are trying to embed a HTML element within an elements attribute list. The browser ma allow it but obviously it will not function correctly.
    – user2417483
    Sep 13, 2013 at 0:33

2 Answers 2

2

Accessing the value based on your markup would be:

var myValue = document.getElementById("tag_IS_System_Agent").textContent
2
  • thank you! While I thought this would work, this returns undefined. Using innerHTML (below) worked.
    – AU_Outpost
    Sep 15, 2013 at 19:14
  • My bad, I forgot that it isn't as fully supported as innerHTML by IE8. As soon as we can retire IE8, we should retire innerHTML as well :) Sep 15, 2013 at 19:47
1

By “the value of an ‘em’ tag”, you apparently mean the content of an em element. If the element has an id attribute, as in your example, you can use the getElementById method of document to access the element node in the DOM. Then you can get the content of the element, serialized as HTML, using the innerHTML property. Note that this will include markup for inner elements, if any. So the expression you would use would be

document.getElementById('tag_IS_System_Agent').innerHTML

Instead of innerHTML, you could use textContent, which gives you just the textual content, without any inner tags. However, this is less widely supported (e.g., not in IE 8). If there is no inner markup, the results are the same, but innerHTML is thus safer.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.