Skip to content Skip to sidebar Skip to footer

How To Process $.get And Catch Html Element Using Jquery?

I'm reading a html document using jQuery. Following is my code. I need to find lang attribute which is an attribute of HTML element. But I have trouble selecting it the way I'm doi

Solution 1:

When you do $(response) on the response text, the html element gets dropped by most (if not all) browsers. To look at it, I see two options:

  1. Process the text as text. Not ideal, but it's not that complicated to parse the attributes on the <html> tag. For instance, this should extract the lang attribute barring the unusual:

    var regex = /<\s*html\s[^>]*lang\s*=\s*["']?([A-Za-z0-9\-]+)/i;
    var matches = regex.exec(str);
    console.log(matches[1]);
    

    Live example | Live source

    Usual caveat: HTML is not a regular language, so you can't reliably parse it with regular expresions. Sometimes a well-tuned regex can extract bits of information from HTML text, and those can be "good enough" when they're rigorously tested with the expected input data, but just beware that they cannot work reliably against all possible HTML source texts.

  2. Rather than using $.get, create a hidden iframe and assign page to it as its src. Then use iframe.contentDocument.documentElement to access the html element, and use getAttribute to read its lang attribute.

    That might look something like this:

    Live copy | Live source | Source of page being loaded

    display("Loading the iframe...");
    var$iframe = $("<iframe>");
    $iframe
      .css({
        position: "absolute",
        left: "-10000px"
      })
      .bind("load", function() {
        var doc = $iframe[0].contentDocument,
            html = doc && doc.documentElement,
            lang = html && html.getAttribute("lang");
        if (lang) {
          display("<code>lang = " + lang + "</code>");
          $iframe.remove(); // Or not, as you prefer
        }
      })
      .appendTo(document.body);
    $iframe[0].src = "http://jsbin.com/imeqij";
    

    (I've had to be somewhat defensive there because JSBin wraps our page in a frame of its own.)

Solution 2:

You can use javascript to do something like this:

<scripttype="text/javascript">var language = document.getElementsByTagName("html")[0].getAttribute("lang");
     alert(language);
</script>

Post a Comment for "How To Process $.get And Catch Html Element Using Jquery?"