0

Let say I have the following DOM element on my page:

<div id="name">Sharon</div>

Q1: Using jQuery, how do I turn the content of #name into a JS variable so I can reuse it in other places on the DOM?

Q2: What's the best way to render a JS variable into my HTML using jQuery? Taking it a step further, if I wanted to remove the content of an element then replace it with the variable what's the best way of doing that?

3 Answers 3

2

To save "Sharon" in a variable, use html():

var content = $('#name').html();

To render it somewhere else (replacing anything that was in that HTML tag before):

$('#example').html(content);

Or, to append it after any content that's in the #example tag, use

$('#example').append(content);

Also look at prepend().

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

Comments

1

Q1: You can just get the HTML with .html():

var content = $('#name').html();

If you're looking for only the text (no styling), then use the .text() function instead:

var content = $('#name').text();

Q2: Setting a parameter for the .html() function sets the HTML of that targeted element:

$('#otherName').html('I am the <i>new</i> content');

Similarly, if you are only setting the text, replace .html() with .text() in my code.

3 Comments

One could also use $('#name').text() to just get the innerText of the element (it's equal to $('#name').html() in this simple case, but may be different for more complex cases)...
Thanks, I've added it to my answer.
Thanks for taking the time to respond, Blender.
0

I know what you mean. with .html() you just get an string of what is inside the element selected and you can't bind events or stuff like that with with solid JavaScript when you select element with jQuery or jQuery then .html().

When you define a variable to a jQuery selector it's not equal with what you define with solid JavaScript.

$('body') == document.getElementsByTagName('body')[0]
//false

using .html() will not solve your problem:

('body').html() == document.getElementsByTagName('body')[0]
//false

.html() gives you an string equals to what's inside the element:

$('body').html() == document.getElementsByTagName('body')[0].innerHTML.toString()
//true

The fact is that jQuery selectors always return an array that contains every element matching the given query event if your query returns one element it will return an array with one element. So with selecting any element of every jQuery selector array you will get an actual DOM element.

$('body')[0] == document.getElementsByTagName('body')[0]

Try this in your browser developer tool to see the result! :D

Comments

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.