1

I want to change the text of a h2. If I use alert, it shows undefined with .html and .val, so, wouldn't it be something like this?:

$("#h2Id").text("new text");

It doesn't work, though. Thanks in advance.

edit: the html is plain simple, as I'm trying to understand why it doesn't work.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="jquery.js"></script>    
    <link href="css/estilos.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="testingStuff.js"></script>
</head>
<body>
    <h2 id="question"> ASD </h2>
</body>

user2484181
  • 49
  • 2
  • 3
  • 8
  • 1
    Post your HTML. `.text()` is the right way to do it. – Blender Jun 13 '13 at 23:33
  • You sure jQuery is loaded? – Mr. Polywhirl Jun 13 '13 at 23:34
  • possible duplicate of [Why does jQuery or a DOM method such as \`getElementById\` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Felix Kling Jun 13 '13 at 23:41
  • 1
    I recommend to read the jQuery help, to learn how to set up your code properly: http://learn.jquery.com/about-jquery/how-jquery-works/. – Felix Kling Jun 13 '13 at 23:41
  • I'm new in programming, but I have already done things with jQuery. More complex things than just changing the text of something. But I just can't find the problem with h- tags :/ And I don't think this is a duplicate of that question. The problem isn't any of the ones displayed there. Thanks anyway :) – user2484181 Jun 13 '13 at 23:57
  • 1
    Unless you show your jquery code to us, I'm going to assume you're literally trying to do `$("#h2Id").text("new text");` when your h2 id is `question` and not `h2Id`. – 000 Jun 14 '13 at 00:04

2 Answers2

10
  1. Make sure jQuery is loaded.

  2. Use the document-ready incantation to let your script wait until the DOM is ready.

    $(function() {
        $("#h2Id").text("new text");
    });
    
  3. http://jsfiddle.net is a wonderful resource for quickly mocking up pages and finding problems.

000
  • 26,951
  • 10
  • 71
  • 101
1

http://jsfiddle.net/4jmEx/

<span id="h2Id">Foo</span>
$('#h2Id').text('Bar');
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132