I need to select '#foo #three' using 'this' to get this result:

cat
dog
cat
Html:

<div id="foo">
 <div id="one">cat</div>
 <div id="two">dog</div>
 <div id="three">mouse</div>
</div>

JS:

$("#foo #three").text($('this div:first').text());

I need this code dynamically

Dani AI

Generated

Common cause: the selector used the literal string "this" instead of the current DOM element, so jQuery was searching for an element called "this" rather than using the event/context node. In jQuery callbacks (or inside an .each()), the raw this is a DOM element; wrap it with $(this) or pass it as the context to jQuery so searches are scoped correctly.

A simple dynamic pattern is: wrap the current container, read the first child text, then set the target element inside that same container. Example:

$('.group').on('click', '.control', function() {
  var firstText = $(this).children().first().text();
  $(this).find('.result').text(firstText);
});

Use .children().first() when the node is a direct child, or .find() for deeper descendants. The alternate form $('selector', this) also restricts the search to the current element. Remember that .text() with no argument reads text from matched elements and with an argument sets their text; see the jQuery .text() docs and jQuery .find() docs for details. For background on this behavior in JS, consult the MDN "this" reference.

’s note that a static direct copy works is fine for one-off changes; ’s nudge to read the API is also apt. For repeatable UI components avoid duplicate IDs—use classes or data attributes and event delegation so the same logic works across multiple instances.

Recommended Answers

All 3 Replies

Unless you are trying to do this dynamically, this is as simple as:

$('#three').text($('#one').text());

I need to select '#foo #three' using 'this' to get this result

Smells like homework to me?

Well learn what the .text() function is and how to use it, because that's very helpful. Only requires one simple google.

Your code essentially does this: #foo -> #three -> div:first, which of course would only match the following HTML:

<div id="foo">
     <div id="three">
        <div>mouse</div>
     </div>
</div>

I think you need to be clear about what you're trying to achive, why you need to achieve it, and why you need to use this.

Notice how this entire answer could've been found on google if you'd have bothered to look, and then asked an actual question when you can't get it working. Lazy.

Thanks all. My problem is solved now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.