1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Help needed in javascript code.. :(

Discussion in 'HTML & Website Design' started by jiah, Mar 23, 2013.

  1. #1
    Hello frnz, I m a working on a website in which i have to get the value(text) of a paragraph element p. I tried inner Html as well as text() functions. But i could not get any value of the "p" element :(

    Please help me , i need to upload this website very soon :(

    /* a scratch of my code */
    //
    <p id=txtpara>
    hello this is a test
    </p>
    //
     
    jiah, Mar 23, 2013 IP
  2. tricks2

    tricks2 Active Member

    Messages:
    427
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    78
    #2
    tricks2, Mar 23, 2013 IP
  3. kk5st

    kk5st Prominent Member

    Messages:
    3,497
    Likes Received:
    376
    Best Answers:
    29
    Trophy Points:
    335
    #3
    I am not a fan of using a library such as jQuery to do what may need only a few lines of code. Will you please post the js code that you've tried? The problem may be something as simple as a syntax error, but we'll never know without seeing the code.

    cheers,

    gary
     
    kk5st, Mar 23, 2013 IP
  4. kk5st

    kk5st Prominent Member

    Messages:
    3,497
    Likes Received:
    376
    Best Answers:
    29
    Trophy Points:
    335
    #4
    test.js
    window.onload = extract;
     
    function extract() {
        if (!document.getElementById) return false;
        var x = document.getElementById('txtpara');
        alert(x.innerHTML);
    }
    Code (markup):
    test.html
    <!DOCTYPE html>
    <html>
      <head>
        <meta content="text/html; charset=utf-8"
              http-equiv="Content-Type" />
     
        <title>test doc</title>
     
        <!-- hack for bug in Web Developer addon for Firefox.  Used for
        development and debugging only-->
        <link rel="stylesheet"
          type="text/css" href="x" />
     
        <style type="text/css">
          body {
            font: 100%/1.5 san-serif;
            margin: 0;
            }
     
          p {
            font-size: 1em;
            }
        </style>
     
        <script type="text/javascript"
            src="test.js">
        </script>
      </head>
     
      <body>
        <p id=txtpara>
          hello this is a test
        </p>
      </body>
    </html>
    Code (markup):
    Since this code works, I'm assuming a syntax error unless you've made an egregious error. There is certainly no reason to use jQuery for less than ten lines of code.

    cheers,

    gary
     
    Last edited: Mar 23, 2013
    kk5st, Mar 23, 2013 IP
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #5
    1) you might have better luck asking in the javascript section of the programming area on these forums.

    2) might help if you used modern/valid markup instead of HTML 3.2, since quotes around parameters are no longer optional. Even in the sleazeball train wreck designed to set coding practices back a decade and a half known as HTML 5

    Gary's example is pretty much working, though it's not really the best way of hooking onload and the logic is a bit wonky :D

    Though it's usually NOT a great idea to be grabbing the contents of an element like that in the first place -- just what is it you are working on that would need to do that?
     
    deathshadow, Mar 23, 2013 IP
  6. kk5st

    kk5st Prominent Member

    Messages:
    3,497
    Likes Received:
    376
    Best Answers:
    29
    Trophy Points:
    335
    #6
    I won't pretend to be a js guru, but to my knowledge that is best practice for a single function. Were there to be multiple functions to run onload, I would have done it differently; but this is a minimal test case.

    Please explain the 'wonkyness' in the logic.

    g
     
    kk5st, Mar 23, 2013 IP
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #7
    The thing is you never know what someone might plug it into, so a 'warning' that it should be done using attachment instead of static function should at least be present. In this day and age of dipshits throwing jquery at EVERYTHING for no good reason, someone just blindly copypasta's that line they will likely break something.

    If you're gonna return false, you should probably also return the value, not just alert it... or better, alert the result of the function... and while javascript generally lets you do it, it's bad practice to declare a call to a function before you actually declare the function itself... makes the browser have to parse the scripting TWICE.

    ... and I can't think the last time I ever saw a browser with javascript without document.getElementById... since there's NO SUCH THING. Did you mean to test for if the element get result existed?

    I'm thinking more like this for that function:
    function extract(targetId) {
    	var target = document.getElementById(targetId);
    	return target ? target.innerHTML : false;
    }
    Code (markup):
    IF one was to keep the alert inside it... test for if the element actually exists, not if the function to get an element by ID exists since, well... Again...

    Of course, I wouldn't use that HTML 5 bull, even just the half-assed/incomplete/meaningless doctype, even in an example. :D

    -- edit --

    Thinking on it, I would call it right before </body> so it is run before the CSS reflow, and to show that it can work being done manually... I would also make the function be passed an ID, and not waste time saying 'else' since the return would be a short circuit.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html
    	xmlns="http://www.w3.org/1999/xhtml"
    	lang="en"
    	xml:lang="en"
    ><head>
    
    <meta
    	http-equiv="Content-Type"
    	content="text/html; charset=utf-8"
    />
    
    <meta
    	http-equiv="Content-Language"
    	content="en"
    />
    
    <title>
    	Extracting an Element's innerHTML with JavaScript Demo
    </title>
    
    </head><body>
    
    <p id="extractThis">
    	hello this is a test
    </p>
    
    <script type="text/javascript"><!--
    
    function extract(targetId) {
    	var target = document.getElementById(targetId);
    	return target ? target.innerHTML : false;
    }
    
    alert(extract('extractThis'));
    
    --></script>
    
    </body></html>
    Code (markup):
    See what I'm saying. A LOT of the things people wait for onload to do really should just be done at runtime, since if you do it right before </body> the DOM is already built.
     
    Last edited: Mar 23, 2013
    deathshadow, Mar 23, 2013 IP
  8. kk5st

    kk5st Prominent Member

    Messages:
    3,497
    Likes Received:
    376
    Best Answers:
    29
    Trophy Points:
    335
    #8
    In the order ref'd:
    1. This is a minimal test case, not a real world coding. I doubt the OP intends to call an alert but that stands in for and proves the method. Likewise there is no point in complicating the onload event handler, so I didn't. Iff there are further questions, they can be dealt with if and when.
    2. In failure it is returning a value: false. There is no alert, the function simply goes gently into the good night, where it either exits javascript or moves to the next instruction. The calling object is free to handle the error.
    3. Whether to have the onload event handler precede the function definition/s is moot. Javascript is not Pascal and is not c/c++ with headers.
    4. The test for getElementById() may be overkill now, but IE7 and earlier had issues.
    5. I agree it would have been a Good Thing to test for the existence of the desired id.
    6. All doctypes are meaningless except for a) triggering quirks or standards mode in the UA, and b) telling the validator which recommendation to validate against. <!DOCTYPE html> triggers standards mode. The validator will use html5 as its model. I have no problem with that. I am finding that some of html5 is useful for some pages and that will guide my coding.
    7. Inline scripting is flat out a poor practice, and I refuse, as with presentation, to mix behavior with the document's structural markup. The external script has already attached the event handler, so as soon as the page is loaded, Bam! the scripted function runs. How is that non-trivially different from your adulteration of the structural markup?
    There, I don't think I missed any of your points.

    cheers,

    gary
     
    kk5st, Mar 23, 2013 IP
  9. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #9
    I'm not a big fan of test cases that aren't "real world coding" drop-in. Admittedly inlining the script like my example did is one of those bad cases...

    It's usually more useful to have the calling object process a proper result too -- though it would be more so if local declarations in JS were allowed everywhere... That's one of the oddities of javascript, you can define MOST everywhere, but not everywhere.

    if (var x=result()) {

    For example being invalid. Pain in the arse. It's almost like they wanted it to be pascal style with everything predeclared, then changed their mind last minute.
    It's not moot when it's an interpreted language -- the implementation either has to store the name reference in a dummy location and plug it in when it actually has it, HANGING the execution until it does, or it has to defer running until it parses all namespace, and then go back through a second time and plug it in -- either way is slower than letting the interpreted language just be in the proper order. Just because you can do it doesn't make it right.

    WHAT ISSUES? Ok, I gotta hear this one becuase sorry... but BULLCOOKIES. I've never heard of any sort of issues with document.getElementById even in Exploder 5 and Nyetscape 4! What are you even on about?!? Well, there is the old versions of IE treating NAME as ID when it shouldn't, but that test would NOT get around that... Even IE 5.0 will return 'true' for that -- not one javascript I've ever even heard of would return false for document.getElementById existing! That's what you are testing for, if it EXISTS -- it EXISTS in every blasted flavor of JS I've ever heard of.

    When it comes to markup it's idiotic BS I can see no legitimate reason to use. All the actually useful stuff is either JS or CSS3 -- which work just FINE in the older documents.

    It is often preferable to run BEFORE onload -- even as external. I wasn't saying to inline it as per the example, but to run it BEFORE onload fires. A great example of this is if you start playing with the DOM or adding stuff with innerHTML. Right before </body> the DOM is pretty much in place -- running markup changes or reading markup then occurs BEFORE CSS is applied... so if you are manipulating the page from scripting, there's no 'script jump' -- it's bad enough having CSS jump without having CSS render, THEN having the scripting force a reflow after that.

    So if you had this as an external extract.js:
    function extract(targetId) {
    	var target = document.getElementById(targetId);
    	return target ? target.innerHTML : false;
    }
    
    alert(extract('extractThis'));
    Code (markup):
    and did this right before </body>
    <script type="text/javascript" src="extract.js"></script>
    Code (markup):
    It would run the alert before onload -- if you were say... adding classes for scripting only behavior and plugging in your scripting only elements (say... a lightbox's loading DIV -- pisses me off seeing that **** in the markup) it would be created before CSS is applied or even in some browsers the first page-flow. A much more desirable behavior than waiting around for everything else to load.

    There's a LOT of times in people's scripts they seem to wait for onload, for no reason I can figure other than to make it take longer, take more code, and not work as well. You can get the same utility most of the time just by running the script at the bottom of the document! Only reason to wait for onload is if you need to do something like pull the rendered width of an element after CSS or images are loaded.
     
    Last edited: Mar 24, 2013
    deathshadow, Mar 24, 2013 IP