Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript $(this).find and innerHTML

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

That works for me. But only for the first 'test' division on my page. I want to add the innerHTML inside where I want it.

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

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

But this second code won't work.

What am I doing wrong?

like image 935
Stan van der Avoird Avatar asked Sep 25 '22 07:09

Stan van der Avoird


People also ask

Is textContent same as innerHTML?

textContents is all text contained by an element and all its children that are for formatting purposes only. innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.

What is the difference between innerHTML and textContent in JavaScript?

innerHTML returns HTML, as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML. Moreover, using textContent can prevent XSS attacks.

What is .innerHTML in JavaScript?

The innerHTML is a property of the Element that allows you to get or set the HTML markup contained within the element: element.innerHTML = 'new content'; element.innerHTML; Code language: JavaScript (javascript)

What are getElementById () and innerHTML properties?

innerHTML = 'Data or content'; getElementById: The getElementById refers to the HTML element using its ID. Data or content: Data is the new content to go into the element.


1 Answers

Because .find() doesn't return the element, but the jQuery object (which doesn't have an innerHTML property). If you're using jQuery, a better method would be to rely on .append():

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

Here is a JSFiddle which demonstrates the .append() solution, as well as doing a console.log() of your find() code so you can open it in your browser's developer console and examine the object for yourself.

like image 174
TML Avatar answered Oct 13 '22 01:10

TML