0

all

I have a HTML input :<h5><font face="times new roman, times, serif" size="7" style="color: #ff9696; ">Sample</font></h5> <ul> </ul>

I want to extract everything and pass to javascript variables. For example, font name, size, style color. Can I use RegEx?

I have tried this but no use:

<html>

    <script>
        var input = '<h5><font face="times new roman, times, serif" size="7" style="color: #ff9696; ">Krishanthan</font></h5> <ul> </ul>';
        var div = document.createElement('div');

        div.innerHTML = input;

        var size = div.getElementsByTagName('size')[0];
        var text = size.innerText || size.textContent;

        alert(text);
    </script>

</html>

Please give me some suggestion...

Thanks.

5
  • Use one of the Javascript HTML Parsers that are already available. Commented Aug 15, 2012 at 22:47
  • if you have to parse arbitrary HTML, than you cannot use regular expressions. If you are using a small subset of HTML constructs, then maybe, but it depends on exactly what features of HTML you are maintaining. If you want more help, you need to give us more details about what you are trying to accomplish. Commented Aug 15, 2012 at 22:48
  • 3
    It seems you have to learn a bit more about the DOM. size is an attribute of the font element, it is not a tag. Get a reference to the font element and use getAttribute to access the attribute. Commented Aug 15, 2012 at 22:52
  • Wouldn't an inline style attribute in a font tag cause the universe to implode or something? @Gobi, read up on more recent HTML practices. Font tags have been considered bad practice for close to 10 years now. They were replaced by CSS which is what you're putting in the style attribute. Commented Aug 15, 2012 at 23:02
  • ... the inline style attribute which is also considered bad practice in most cases. Commented Aug 15, 2012 at 23:08

1 Answer 1

3

You have the right idea, but you are treating size like an element, whereas actually it is an attribute of the font element.

var input = '<h5><font face="times new roman, times, serif" size="7" style="color: #ff9696; ">Krishanthan</font></h5> <ul> </ul>';
var div = document.createElement('div');

div.innerHTML = input;

var fontEl = div.getElementsByTagName('font')[0];
var size = fontEl.getAttribute('size');

alert(size);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank-you so much yeah that works...........!!!!! It seems like I am very poor in DOM :(. can you suggest books for learning HTML DOM from basic... Thanks again

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.