Solved

jquery, difference between text() and html()

Posted on 2014-11-26
18
105 Views
Last Modified: 2014-11-26
Let me qualify my question. I know the difference between text() and html() when WRITING in that text() outputs ascii as text, while html() will output ascii as html (as demonstrated by the FIRST brief sample. My question is in READING (see the SECOND example).

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript">
    $(function(){
      $("#div1").html('<a href="example.html">Link</a><b>hello</b>');
      $("#div2").text('<a href="example.html">Link</a><b>hello</b>');
    });
  </script>
</head>

<body>

<div id="div1"></div>
<div id="div2"></div>

</body>
</html>

Open in new window


This next sample attempts to READ the text() and html() and simply outputs the values to the <result1> and <result2> tags:

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript">
    $(function(){
		$("result1").html($("#div1").html());
		$("result2").html($("#div1").text());
    });
  </script>
</head>

<body>

<div id="div1">This is div1</div><p/>

<result1></result1><br/>
<result2></result2>

</body>
</html>

Open in new window


They look the same visually, but I know they're internally not. And I know that because of this actual example I was playing around with (which looks long but really isn't, it's just a bunch of "lorem ipsum" text. All I'm trying to do is look for all <h3> tags and make bookmark links out of them. Look for my comments very near the beginning, all in UPPER CASE where I show the actual line I'm have a question on:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Creating Automatic Bookmarks</title>
    <script type="text/javascript" src="../jquery-1.9.1.js"></script>
    <script type="text/javascript">
        $("document").ready(function() {
            buildBookmarks('h3', 'header');
        });

        function buildBookmarks(strWhichTag, sBookMarkNode) {
            var cAnchorCount = 0;

            // create the list that will hold the bookmark links
            var oList = $("<ul id='bookmarksList'>");

            // for each one of the header tags, create a new named anchor and insert it into
            // the header tag. Then add a new link to the list that points to the named anchor
            $(strWhichTag).each(function() {
                $(this).html("<a name='bookmark" + cAnchorCount + "'></a>" + $(this).html());
/***********HERE IS MY COMMENT
IN THE NEXT LINE, IF YOU REPLACE $(this.text() WITH $(this).html(), THE TEXT WILL NO LONGER APPEAR AS HYPERLINKS. SO CLEARLY, THERE IS A DIFFERENCE BETWEEN text() AND html(), EVEN THOUGH THEY LOOK IDENTICAL WHEN OUTPUT TO THE SCREEN, AND I WANT TO UNDERSTAND WHAT'S GOING ON BEHIND THE SCENES.
***********************/
                oList.append($("<li><a href='#bookmark" + cAnchorCount++ + "'> " + $(this).text() + "</a></li>"));
            });

            // now find the ID of the bookmark container and append it
            $("#" + sBookMarkNode).append(oList);
        }
    </script>
</head>
<body>
    <div id="header">
        <h1>
            Automatic Bookmark Headings Example</h1>
        <h2>
            Using jQuery to Extract Existing Page Information</h2>
        <p id="byline">&nbsp;</p>
    </div>
    <div id="intro">
        <h3>
            Introduction</h3>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
            eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea
            takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur
            sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
            aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et
            ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor
            sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
            eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
        <p>
            Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat,
            vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo
            dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
            ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
            diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
            diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita
            kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum
            dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore
            dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet
            clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua.
            est Lorem ipsum dolor sit amet.
        </p>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr,
            sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
            sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
            clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem
            ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
            invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
        <a href="#header" title="return to the top of the page">Back to top</a>
    </div>
    <div id="ingredients">
        <h3>
            At Vero Eos et Accusam et Justo Duo Dolores</h3>
        <p>
            At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
            no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure
            dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
            eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui
            blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
            velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
            eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit
            augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend
            option congue nihil imperdiet doming id quod mazim placerat facer possim assum.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat.
        </p>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr,
            sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
            sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
            clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem
            ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
            invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr,
            sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
            sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
            clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem
            ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
            invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
        <a href="#header" title="return to the top of the page">Back to top</a>
    </div>
    <div id="prepare">
        <h3>
            Lorem Ipsum Dolor sit Amet</h3>
        <p>
            Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat,
            vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo
            dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
            ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
            diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
            diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita
            kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum
            dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore
            dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet
            clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua.
            est Lorem ipsum dolor sit amet.
        </p>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
            eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea
            takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur
            sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
            aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et
            ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor
            sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
            eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
        <pre>  function hideDivs()
  {
    var divs = document.getElementsByTagName(&#34;div&#34;);
    for(var i=0; i &#60; divs.length; i++)
    {
      var div = divs[i];
      var id = div.id;
      if ((id != &#34;header&#34;) &#38;&#38;
          (id != &#34;footer&#34;))
      {
        div.style.display = &#34;none&#34;;
      }
    }
  }

  window.onload = function()
  {
    hideDivs();
  }</pre>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
            eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea
            takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur
            sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
            aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et
            ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor
            sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
            eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
        <pre>  if (!document.getElementsByTagName) return null;</pre>
        <p>
            At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
            no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure
            dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
            eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui
            blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
            velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
            eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit
            augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend
            option congue nihil imperdiet doming id quod mazim placerat facer possim assum.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat.
        </p>
        <pre>  function hideDivs(<strong>exempt</strong>)
  {
    if (!document.getElementsByTagName) return null;
    <strong>if (!exempt) exempt = &#34;&#34;;</strong>
    var divs = document.getElementsByTagName(&#34;div&#34;);
    for(var i=0; i &#60; divs.length; i++)
    {
      var div = divs[i];
      var id = div.id;
      if ((id != &#34;header&#34;) &#38;&#38;
          (id != &#34;footer&#34;) <strong>&#38;&#38; (id != exempt)</strong>)
      {
        div.style.display = &#34;none&#34;;
      }
    }
  }

  window.onload = function()
  {
    hideDivs(<strong>&#34;intro&#34;</strong>);
  }</pre>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr,
            sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
            sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
            clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem
            ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
            invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
        <pre>  function fixLinks()
  {
    if (!document.getElementsByTagName) return null;
    var anchors = document.getElementsByTagName(&#34;a&#34;);
    for(var i=0; i &#60; anchors.length; i++)
    {
      var a = anchors[i];
      var href = a.href;
      if ((href.indexOf(&#34;#&#34;) != -1) &#38;&#38;
          (href.indexOf(&#34;header&#34;) == -1))
      {
        var index = href.indexOf(&#34;#&#34;) + 1;
        href = &#34;javascript:show('&#34; +
               href.substring(index) + &#34;');&#34;;
        a.setAttribute(&#34;href&#34;,href);
      }
    }
  }</pre>
        Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat,
        vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo
        dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
        ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
        diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
        diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita
        kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
        <br />
        <p>
            Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat,
            vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo
            dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
            ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
            diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
            diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita
            kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Now, about
            that <code>show</code> function&#8230; This is a simple function that uses the <acronym
                title="Document Object Model">DOM</acronym> to show an identified node and hide
            the rest. We already have a great multi-purpose hiding function in <code>hideDivs</code>,
            so all we need is the &#8220;show&#8221; part. Here&#8217;s the code:</p>
        <pre>  function show(what)
  {
    if (!document.getElementById) return null;
    showWhat = document.getElementById(what);
    showWhat.style.display = &#34;block&#34;;
    hideDivs(what);
  }</pre>
        <p>
            At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
            no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure
            dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
            eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui
            blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
            velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
            eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit
            augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend
            option congue nihil imperdiet doming id quod mazim placerat facer possim assum.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat.
        </p>
        <a href="#header" title="return to the top of the page">Back to top</a>
    </div>
    <div id="decorate">
        <h3>
            Stet Clita Kasd Gubergren</h3>
        <p>
            At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
            no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure
            dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
            eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui
            blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
            velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
            eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit
            augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend
            option congue nihil imperdiet doming id quod mazim placerat facer possim assum.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat.
        </p>
        <pre>  function hideDivs(exempt)
  {
    if (!document.getElementsByTagName) return null;
    if (!exempt) exempt = &#34;&#34;;
    var divs = document.getElementsByTagName(&#34;div&#34;);
    for(var i=0; i &#60; divs.length; i++)
    {
      var div = divs[i];
      var id = div.id;
      if ((id != &#34;header&#34;) &#38;&#38;
          (id != &#34;footer&#34;) &#38;&#38;
          (id != exempt))
      {
        <strong>div.className = &#34;hidden&#34;;</strong>
      }
    }
  }

  function show(what)
  {
    if (!document.getElementById) return null;
    showWhat = document.getElementById(what);
    <strong>showWhat.className = &#34;&#34;;</strong>
    hideDivs(what);
  }

  window.onload = function()
  {
    hideDivs("intro");
    fixLinks();
  }</pre>
        <p>
            At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
            no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure
            dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
            eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui
            blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
            velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
            eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit
            augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend
            option congue nihil imperdiet doming id quod mazim placerat facer possim assum.
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
            euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
            minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip
            ex ea commodo consequat.
        </p>
        <pre>  function fixLinks()
  {
    if (!document.getElementsByTagName) return null;
    var anchors = document.getElementsByTagName(&#34;a&#34;);
    for(var i=0; i &#60; anchors.length; i++)
    {
      var a = anchors[i];
      var href = a.href;
      <strong>if (href.indexOf("#header") != -1) { a.className = "alt"; } else </strong>if ((href.indexOf(&#34;#&#34;) != -1) &#38;&#38;
                  (href.indexOf(&#34;header&#34;) == -1))
      {
        var index = href.indexOf(&#34;#&#34;) + 1;
        href = &#34;javascript:show('&#34; +
               href.substring(index) + &#34;');&#34;;
        a.setAttribute(&#34;href&#34;,href);
      }
    }
  }</pre>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat.
        </p>
        <pre>  .alt {
    display: none;
  }</pre>
        <a href="#header" title="return to the top of the page">Back to top</a>
    </div>
    <div id="serve">
        <h3>
            Tempor Invidunt ut Labore et Dolore
        </h3>
        <p>
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
            tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr,
            sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
            sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
            clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem
            ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
            invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
        </p>
    </div>
</body>
</html>

Open in new window

0
Comment
Question by:elepil
  • 10
  • 8
18 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
.text will only grab the text from the target i.e. anything between HTML tags

.html will grab everything from the target - text and html
0
 

Author Comment

by:elepil
Comment Utility
Gary, I know that, but I am puzzled why the SECOND example is not showing that.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Works fine for me
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Here's a test fiddle

http://jsfiddle.net/81mf4fgt/1/
0
 

Author Comment

by:elepil
Comment Utility
I don't know why it works in that website you linked me to. It doesn't work for me, and I've tried it with both Dreamweaver CC and Netbeans 8.0. Changing the text() to html() would output the <h3> titles as text, not links. Have you tried it with a text editor in your local machine?
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Yes I tried it locally as well.

Do you have a link to the page or can you put up a test page?
0
 

Author Comment

by:elepil
Comment Utility
Oh wait a minute, I checked your jsfiddle.net again, you had it wrong. You were supposed to interchange between .text() and .html on that line. If you change it to .text(), it won't work.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
That's because .text() doesn't add HTML as HTML - it adds it as plain text.
HTML needs to be added to the DOM for it to work

e.g.
< will become &lt;
0
 

Author Comment

by:elepil
Comment Utility
I understand what you're saying. But if you looked at my second example where I tried to output the results of text() and html() on the same tag, I see no visual difference. I know there is a difference internally, but I'm trying to get a visual difference in output, which I can't. Run my second example and you will see what I mean. I am pasting it for you again:

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript">
    $(function(){
		$("result1").html($("#div1").html());
		$("result2").html($("#div1").text());
    });
  </script>
</head>

<body>

<div id="div1">This is div1</div><p/>

<result1></result1><br/>
<result2></result2>

</body>
</html>

Open in new window

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 58

Expert Comment

by:Gary
Comment Utility
In that example it doesn't really matter since it is only text anyway, there is no HTML so both lines produce the same output
0
 

Author Comment

by:elepil
Comment Utility
But with the actual example which was supposed to produce bookmark links, it apparently had a difference.

In other words, what's puzzling me is that how can something that has an ostensible effect on the results in one example appear identical when outputted? I was expecting that maybe one will output <h3>This is div1</h3> while the other would output just "This is div1". But that is not the case as evidenced with the example you just tried out, and the whole purpose of my post was to get an explanation why that is.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
In the above example
<div id="div1">This is div1</div>

.text() and .html() will both get "This is div1" (there is no html to worry about)

if you had instead
<div id="div1"><a href="somelink.php">This is div1</a></div>

then
.text() would get "This is div1"
.html() would get "<a href="somelink.php">This is div1</a>"
.
0
 

Author Comment

by:elepil
Comment Utility
That's what I thought, but the THIRD example I provided disproves what you just said. The jquery was looking for <h3> tags, and those look like <h3>title text</h3>, which has no html in its innerHTML. Given your explanation, you would think both html() and text() should've just picked up "title text" because there is no html to grab inside, correct? But somehow, the example fails when I change text() to html(), and that's what I need an explanation for.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Ok, looked at your code a bit more and see where you are going wrong
You were initially changing the HTML of the paragraph headers to add a link.
A bit later you grab the HTML (when using .html) of the paragraph header to add the link to the top of the page - problem is those headers already have a link now, so you cannot add another link inside a link ergo it was getting screwed up.
See this amendment where I assign the HTML to a variable (title) and then use this variable when creating the bookmarks and the links.
http://jsfiddle.net/81mf4fgt/3/
0
 

Author Comment

by:elepil
Comment Utility
I don't see your "amendment", unless you were supposed to provide a link.

There are two anchor tags being created, both are mutually exclusive. The first is created at the beginning of the <h3> tags just to serve as a target. The second is at the top of the page with the header text presented as links. So I don't understand what you meant by my "adding a link inside a link".

The link to serve as the target is:

$(this).html("<a name='bookmark" + cAnchorCount + "'></a>" + $(this).html());

Open in new window


As you can see, the above is an end in itself. No links are being nested, if that was what you meant.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
http://jsfiddle.net/81mf4fgt/3/

both are mutually exclusive
No they're not

Here you change the HTML of the headers to include an anchor
$(this).html("<a name='bookmark" + cAnchorCount + "'></a>" + $(this).html());

A bit later you append your list with the same header but now it includes an anchor tag
oList.append($("<li><a href='#bookmark" + cAnchorCount++ + "'> " + $(this).text() + "</a></li>"));
You can't have a link inside a link and so the HTML is "corrupted" as it is now invalid.
Browsers will automatically close both links immediately and ignore the the other closing tags (</a>) to make the code valid
0
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
Comment Utility
... so your top links actually end up like this

<li>
<a name="bookmark0"></a>
<a href="#bookmark0"></a>
Introduction
</li>
0
 

Author Closing Comment

by:elepil
Comment Utility
When I saw your sample output of the two consecutive anchor tags, I checked it out with Firebug and saw it. I have to get into the habit of doing that first at the first sign of trouble.

I got it now. Crap, that wasn't my code, it was an example code from what I was studying. But I do understand perfectly now what was happening. When I switched the text() to html(), it picked up the anchor tag that was created in the previous line which it otherwise would NOT have done if I had just used text().

Thanks for your help!
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now