Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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", "");
   } 
like image 597
Samuel Beckett Avatar asked Dec 01 '10 14:12

Samuel Beckett


People also ask

How can I get the ID of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I find the ID of a selected element?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Can I use id in jQuery?

id is not a valid jquery function. You need to use the . attr() function to access attributes an element possesses. You can use .


1 Answers

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?

like image 78
Pointy Avatar answered Oct 17 '22 23:10

Pointy