开发者

How to create a javascript variable from a DOM element using jQuery

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: Wh开发者_JS百科at'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?


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().


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜