Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery - Selecting a text box before a span tag with certain CSS class
    text
    copied!<p>I am a beginner in jQuery. It would be great if somebody could help me with this. I am not sure what's going wrong here. </p> <p>This is what I am trying. I have a element with class as "spanClass1". Before this element there is another element and a text box element. My requirement is to scroll to that text box element and gain focus to the element. And also I added some css to see the change happening. But the problem is that the code above doesn't seem to be working. If I replace the selector in .prev(..) to 'span', it works. Am I missing something? It would be really helpful if somebody could help me with this.</p> <pre><code>&lt;html&gt;&lt;br /&gt; &amp;lt;head&amp;gt;&lt;br /&gt; &amp;lt;title&amp;gt;&lt;br /&gt;jQuery&amp;lt;/title&amp;gt;&lt;br /&gt; &amp;lt;script type="text/javascript" language="javascript" src="jquery.js"&amp;gt;&lt;br /&gt;&amp;lt;/script&amp;gt;&lt;br /&gt; &amp;lt;script type="text/javascript" language="javascript"&amp;gt;&lt;br /&gt; $(document).ready(function() {&lt;br /&gt; var elem = $('.spanClass1').get();&lt;br /&gt; alert(elem.length);&lt;br /&gt; alert("Text box elements " + $('input[type=text]').get().length);&lt;br /&gt; if (elem.length &amp;gt; 0)&lt;br /&gt; {&lt;br /&gt; var elem1 = $(elem[0]).prev('input[type=text]');&lt;br /&gt; $(this).scrollTop($(elem1).position().top);&lt;br /&gt; $(elem1).css('background-color','red');&lt;br /&gt; $(elem1).focus();&lt;br /&gt; }&lt;br /&gt; });&lt;br /&gt; &amp;lt;/script&amp;gt;&lt;br /&gt; &amp;lt;/head&amp;gt;&lt;br /&gt; &amp;lt;body&amp;gt;&lt;br /&gt; &amp;lt;br /&amp;gt;&lt;br /&gt; &amp;lt;div&amp;gt;&lt;br /&gt; &amp;lt;input type="text" id="text1" value="test" class="selected"&amp;gt;&lt;br /&gt;&amp;lt;span id="elem4" class="sClass1"&amp;gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;lt;/span&amp;gt;&lt;br /&gt;&amp;lt;span id="elem5" class="spanClass1"&amp;gt;&lt;br /&gt;This is a test&amp;lt;/span&amp;gt;&lt;br /&gt;&amp;lt;br /&amp;gt;&lt;br /&gt; &amp;lt;/div&amp;gt;&lt;br /&gt; &amp;lt;/body&amp;gt;&lt;br /&gt; &lt;/html&gt; </code></pre> <p>Thanks in advance.</p> <p>Regards, Karthik</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload