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

4

5 回答 5

4
var val=document.getElementById('strike').innerHTML; 
    alert(val);
于 2012-07-30T11:07:44.123 回答
0

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

于 2012-07-30T11:08:58.683 回答
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.

于 2012-07-30T11:09:30.267 回答
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; 
于 2012-07-30T11:11:36.537 回答
0
var val=document.getElementById('strike').innerHTML; 
于 2012-07-31T07:10:18.310 回答