Javascript $ (this) .find and innerHTML

 document.getElementById("test").innerHTML += " hello two";

This works for me. But only for the first section "test" on my page. I want to add innerHTML inside where I want.

so I have a button, and when I click it, something like this should happen:

$this.find("#test").innerHTML += " hello two";

But this second code will not work.

What am I doing wrong?

+4
source share
3 answers

Because . find () does not return an element, but a jQuery object (which does not have a property innerHTML). If you use jQuery, the best method would be to rely on . Append () :

$("#test").append(" hello two");

- JSFiddle, .append(), console.log() find(), .

+3

jQuery jQuery, DOM

jQuery .get(), DOM, jQuery, DOM, .innerHTML.

jQuery ( .text() .append()) . :

$(function () {
  
  // Following the OP pattern of using `.find()`...
  // you have to use `.get()` to retrieve the DOM element from the jQuery Object.
  $(document).find('#test').get(0).innerHTML += ' hello two';
  
  // Or simply use the jQuery selector to directly select the target element.
  // You may also just use square bracket notation to retrieve the DOM element.
  $('#test')[0].innerHTML += ' hello three';
  
  // jQuery `.text()` method may also be used to get & set the text:
  // Inefficiently, as seen here.
  $('#test').text($('#test').text() + ' hello four');
  
  // Or with a function that returns a new string value to set.
  $('#test').text(function (i, str) { return str + ' hello five' });
  
  // Or with fancy pants ES6 arrow function notation.
  $('#test').text((i, str) => str + ' hello six');
  
  // But using jQuery `.append()` method is best for this scenario.
  $('#test').append(' hello seven');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">Hello world</p>
Hide result
+1

$this.find("#test").innerHTML += " hello two"; $(this).find("#test").append(" hello two");, - ..innerHTML jquery

$("button").click(function() {
    $("the place you want").append($("#test").text());
});

This $("the place you want")can be an attribute of tagnameeg $("p")or ideg $("#first_p")or nameeg $("[name='name_of_p']")element

$(document).ready(function(){
    $("button").click(function() {
        $("p").append(" hello two");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button>Click me</button>
<p>Good morning,</p>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1629711/


All Articles