简体   繁体   中英

Get inner text of an element

I'm trying to figure out a way to get the text following the element, in JavaScript, but without the classicals workarounds. My markup is:

<div class='el'>
  <span class='fa fa-user'></span> Dollynho
</div>

I just want the word 'Dollynho', but without spliting the innerHTML of .el . I can do it this way:

var xs = document.getElementsByClassName('el')[0]
console.log(xs.split('>')[2].trim()) # => "Dollynho"

Can I do it in a cleaner way? (No-regex, pls)

Thanks in advance!

var xs = document.getElementsByClassName('el')[0];
xs.innerText;

in firefox you may need to user textContent

Iterate through all the childNodes and grab the content of the child nodes of type text, then remove the spureous \\n

var childNodes = document.getElementsByClassName('el')[0].childNodes;

var textContent = "";
for(var i=0; i<childNodes.length; i++) {
    if(childNodes[i].nodeType==3  ) {
        textContent+=childNodes[i].data;
    }
}
textContent= textContent.replace(/\r?\n|\r/g,"");

Fiddle: http://jsfiddle.net/53rx1t0o/11/

Use this in your script code if you want the html of your .el class is retrieved:

var x = $(".el").html();

您可以使用jQuery获取文本

$(".el").text()

Depending on your IE support needs you could use textContent https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent

var xs = document.getElementsByClassName('el')[0]
console.log(cs.textContent)  # => "Dollynho"

IE has .innerText which works similarly but with some caveats (described on the textContent page above)

http://msdn.microsoft.com/en-us/library/ie/ms533899(v=vs.85).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM