2

I want to read an html tag which has formatted text. For example

<p id="strike" onMouseOver="getP()><b>Hello</b></p> // paragraph Tag with formatted text

if i am calling a function,

 function getP()
 {  
       var val=document.getElementById('strike').value; 
    alert(val);
 } 

am getting undefined in alert, how to get the exact bold formatted text or bold tag with text....Please help me out in this

2
  • 1
    .textContent returns the plaintext, .innerHTML returns the HTML. There's no way to alert a boldfaced piece of text. Commented Jul 30, 2012 at 11:08
  • @Rob: I don't think he wants to alert it formatted, just to retrieve the text from the b element, and alert that. Commented Jul 30, 2012 at 15:21

5 Answers 5

4
var val=document.getElementById('strike').innerHTML; 
    alert(val);
Sign up to request clarification or add additional context in comments.

Comments

0

Use alert(document.getElementById('strike').innerHTML);

Comments

0

p does not have value property. You need to get the first childNode which is b, and access the innerHTML property.

   var val=document.getElementById('strike').childNodes[0].innerHTML; 

Comments

0

I'd suggest using:

function getP() {  
   var el = document.getElementById('strike').getElementsByTagName('b')[0],
       text = el.textContent ? el.textContent : el.innerText;
   alert(text);
}

JS Fiddle demo.

Updated the above, and generalised some:

<script type="text/javascript">
function getP(el,tagtype) {
    if (!el || !tagtype) {
        return false;
    }
    else {
        var textFrom = el
    .getElementsByTagName(tagtype)[0],
            text = textFrom.textContent ? textFrom.textContent : textFrom.innerText;
   console.log(text);
    }
}
</script>

<p id="strike" onMouseOver="getP(this, 'b')"><b>Hello</b></p>​

JS Fiddle demo.

1 Comment

Don't use el.textContent to check whether 'textContent' is supported. When it's an empty string, It will be false when coerced to a boolean. The correct way to check whether it's supported is document.textContent === null. This follows from the fact that a node of type DOCUMENT_NODE has a textContent property which is equal to null (per specification). Example: text = el[document.textContent === null ? 'textContent' : 'innerText'];
0
var val=document.getElementById('strike').innerHTML; 

Comments

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.