Search code examples
javascriptdomparser

How to filter out HTML tags from within a div tag using JavaScript


I have this HTML code:

<div>
    756
    <span></span>
</div>

Using JavaScript I want to retrieve the number 756 from within the div tag and increment it by 1. What is the best method of filtering out the <span> from within the div tags so I get only the number?


Solution

  • Try this:

    var div = document.getElementsByTagName("div")[0],
        content = div.textContent || div.innerText;
    

    textContent is supported by all browsers except IE8- and innerText is supported in all browsers except FF4-. So using both, you should get a stable result.

    http://www.quirksmode.org/dom/w3c_html.html

    Both properties return the text content with stripped HTML tags.

    Example: http://jsfiddle.net/HnWxk/ (tested in chrome/ff/ie7)

    Now, if you want to increment it, just do:

    content++;
    

    It should cast a Number: http://jsfiddle.net/HnWxk/3/