1

I have this code that gives me all the LABEL inside the HTML element with id "nuovaImmagine":

$.labelImmagine = $("#nuovaImmagine1").find("label");

I know that inside $.labelImmagine there are 3 labels. If I do alert($.labelImmagine.size()); the alert shows "3";

Now I have to get the first element of the array and edit the text of the label.

I tried both $.labelImmagine.get(0).text("Hello") and $.labelImmagine[0].text("Hello") but none works.

Any idea?

Thank you

1
  • 2
    $.labelImmagine.eq(zeroBasedIndex).text('Hello World!'). Commented Apr 19, 2016 at 14:37

4 Answers 4

1

You don't want the HTML element, you want the jQuery object of that HTML element. I can tell because you're trying to use jQuery methods on it.

Both $().get(0) and $()[0] give you DOM nodes. You need $().eq(0) or $().first(), which return a jQuery object.

Sign up to request clarification or add additional context in comments.

Comments

1

It's a bad idea to pollute the $ namespace. I'd rather use

var $labelImmagine = $("#nuovaImmagine1").find("label");
//   ^--- no dot.   

But yea.... otherwise, simply do like

$.labelImmagine = $("#nuovaImmagine1").find("label");
$.labelImmagine.eq(0).text("WOOOOO");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nuovaImmagine1"><label>TEST</label></div>

and all wrapped inside an IIFE or document ready scope:

jQuery(function($) { // DOM ready and $ alias secured
    /**/
});

Comments

1

You can use .eq() and change its text with .text()

$.labelImmagine = $("#nuovaImmagine1").find("label");
$.labelImmagine.eq(0).text('some text');

Check the below snippet

$.labelImmagine = $("#nuovaImmagine1").find("label");
$.labelImmagine.eq(0).text('some text')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nuovaImmagine1">

  <label>label 1</label>
  <br>
  <label>label 2</label>
  <br>
  <label>label 3</label>
  <br>
</div>

Comments

0

If you want to continue using Jquery you would need to re-'jqueryify' the element. For example

$($.labelImmagine[0]).text("Hello")

This is because by selecting the element by index it is no longer a jquery object, and thus .text() doesn't exist.

Otherwise you could use

$.labelImmagine[0].innerHTML = "Hello"

2 Comments

It's works. I didn't give you the downvote, it wasn't me
Sorry - I wasn't implying it was you! I was asking in general if I needed to expand on something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.