Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  121] [ 2]  / answers: 1 / hits: 49068  / 14 Years ago, wed, december 1, 2010, 12:00:00

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, );
}

More From » jquery

 Answers
47

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?


[#94776] Monday, November 29, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyreek

Total Points: 421
Total Questions: 115
Total Answers: 102

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;