Quiero leer una etiqueta html que tiene texto formateado. usando javascript

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

preguntado el 30 de julio de 12 a las 12:07

.textContent returns the plaintext, .innerHTML returns the HTML. There's no way to alert a boldfaced piece of text. -

@Rob: I don't think he wants to alert it formatted, just to retrieve the text from the b element, and alert that. -

5 Respuestas

var val=document.getElementById('strike').innerHTML; 
    alert(val);

Respondido 30 Jul 12, 12:07

Utilice las alert(document.getElementById('strike').innerHTML);

Respondido 30 Jul 12, 12:07

p no tiene value property. You need to get the first childNode which is by acceder al innerHTML propiedad.

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

Respondido 30 Jul 12, 12:07

Sugeriría usar:

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

Demostración de JS Fiddle.

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>

Demostración de JS Fiddle.

Respondido 30 Jul 12, 12:07

No use el.textContent para comprobar si '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 tiene un textContent property which is equal to null (Para especificación) Ejemplo: text = el[document.textContent === null ? 'textContent' : 'innerText']; - Rob W

var val=document.getElementById('strike').innerHTML; 

Respondido 31 Jul 12, 08:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.