Samuel Beckett
Samuel Beckett

Reputation: 223

Jquery - Get element by id constructing the id in string

I have a trouble using an element with jquery. I am constructing the name in a var such as:

var myId = "#" + myGotId;

$(myId).attr("title", "changed");

$(myId) is returning empty. I would want to get my element by id but constructing my Id dynamically joining strings.

edit by @Pointy — additional code supplied in a comment by the OP:

var form = $('form#formDefaultValue');
$(':submit', form).click(function(event) {
  event.preventDefault();
  $.post(form.attr('action'), form.serialize(), function(data, status, XMLHttpRequest) {
    if (status == 'success') {
      $("#msgInformation").html("Your changes have been successfully saved.");
      jQuery("#spanDefaultValue").attr("class", "db");
      var g = indexNodeSelected;
      g = g.replace("\\", "\\\\\\\\");
      $('#'+ g).find("span").attr("class", "");
   } 

Upvotes: 16

Views: 49931

Answers (4)

Pointy
Pointy

Reputation: 413702

I don't know exactly what is happening because you have not posted much code, but make sure that your Javascript code is running after the element with your target "id" value has been included in the DOM. If you have this:

<html>
  <head>
    <script>
      var myId = '#' + myGotId;
      $(myId).whatever();

then that won't work because the actual page will not have been seen when your code runs.

Instead, try this:

  <script>
    $(function() {
      var myId = '#' + myGotId;
      // ...
    });

It is also important to make sure that your "myGotId" string is exactly the value you expect (that is, the value coded into the "id" attribute of your target element).

edit If you think that you're correctly constructing the "id", then you could try this as an alternative:

$(document.getElementById(myGotId)).whatever()

In other words, you can "wrap" a plain DOM element up in a jQuery object by just passing to the $() function. If that works, then the problem could be that your "id" value is somehow confusing the selector engine. Does the "id" value contain "." by any chance?

Upvotes: 24

Mike Grace
Mike Grace

Reputation: 16924

The reason your jQuery isn't working as expected is because it is executing before the DOM is fully loaded into the browser.

Put your jQuery code in a document ready function and it will work.

$(document).ready(function () {
  // code that will run once the entire DOM is loaded into the browser
});

Example webpage => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-get-element-by-constructed-string.html

Example Firebug console output

Example Firebug console output

What happened here?

  1. as soon as the script loaded it started executing
  2. console.log output 'Dom may not be ready yet'
  3. jQuery selector returned nothing
  4. DOM fully loaded into browser starting the document ready function
  5. jQuery selector returned expected results

Why?

Scripts can load before a browser has a chance to parse the HTML on a page. Before a browser can fully parse the DOM and build it's DOM tree it won't be able to tell you if an element exists or not. This is why running the jQuery selector before the document is ready will often result in unexpected results.

Example script

//run possibly before DOM is loaded into browser
var selector = "#crazy-image";
console.log("DOM may not be ready yet");
console.log($(selector));
$(document).ready(function () {
  // code that will run once the entire DOM is loaded into the browser
  console.log("DOM ready");
  console.log($(selector));
});

Upvotes: 4

Steren
Steren

Reputation: 7909

As this example show, your code should be working : Make sure you execute the script after the element you want to get has been created. Make sure the id is correct.

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>

<div id="mydiv">Hello</div>

<script>
var myGotId = 'mydiv';
var myId = "#" + myGotId;
$(myId).attr("title", "changed");
</script>

</body>
</html>

Upvotes: 0

ryanulit
ryanulit

Reputation: 5001

Do you need the extra variable? Try without it, like this:

$("#" + myGotId).attr("title", "changed");  

Upvotes: 3

Related Questions