-2
<p id="test">lol</p>

<script type="text/javascript">
var text = $('test').text();
var comparingText = 'lol';

if (text == comparingText) {
document.write('haha');
}
</script>

Why will not this work ? Have even tried using "IF NOT"..

0

2 Answers 2

4

You are attempting to grab a <test> tag, not a tag with ID test. To get the tag by ID, you need a # symbol: $('#test')

HOWEVER: Using jQuery as a selection engine is overkill and inefficient. Here is your code in vanilla JavaScript:

if( document.getElementById('test').firstChild.nodeValue == "lol")
  document.write("haha");
Sign up to request clarification or add additional context in comments.

5 Comments

Yeah, but I've already downloaded jquery.js, I don't know if I can be bothered to download vanilla.js too.
"Vanilla JS" is a term that refers to having NO extension of any kind. Just plain, raw JavaScript that the browser can run without having to download any kind of extension. It's annoying that someone called an extension that, since it's completely contradictory.
+1 for taking my comment seriously. (Did you read the page I linked to, or have I just fallen for your trick too?) Seriously though, +1 for a good answer.
Oh, okay, I get it. Haha... Silly peoples make silly sites :D
It doesnt work? if( document.getElementById('test').firstChild.nodeValue == "lol") { document.write("haha"); } This gives me no error, but it doesnt write anything ? ​
0

You are not getting element by id, should be:

var text = $('#test').text();

And it would be better to write your script in DOM load event:

$(function(){
    var text = $('#test').text();
    var comparingText = 'lol';

    if (text == comparingText) {
        document.write('haha');
    }
);

Fiddle: http://jsfiddle.net/eedUs/1/

1 Comment

"And it would be better to write your script in DOM load event" - Why is that? Putting a script block at the end of the body is a reliably and widely used practice. (Not that the OP said he has the script at the end, but he does have it after the element in question so it will work once he takes your advice about the selector.)

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.