What is the difference between .empty().append() and .html()? - javascript

Using jQuery, what's the performance difference between using:
$('#somDiv').empty().append('text To Insert')
and
$('#somDiv').html('text To Insert')
?

$('#somDiv').html(value) is equivalent to $('#somDiv').empty().append(value).
Source: jQuery source.

.html will overwrite the contents of the DIV.
.append will add to the contents of the DIV.

difference between append() and html() in jQuery
.append() and .html() are the most useful methods in jQuery. But these are far different from one another, .append() add some value to the existing one. Where .html() do the same but it removes the old value first.
Here is an example:
<ul id="test">
<li>test</li>
</ul>
Now I will use .append() to add one <li>, For that I will write:
<script type="text/javascript>"
jQuery("#test").append("<li>test1</li>");
</script>
The output of this jQuery will be:
<ul id="test">
<li>test</li>
<li>test1</li>
</ul>
Now if I use .html() to add one <li>, For that I will write:
<script type="text/javascript>"
jQuery("#test").html("<li>test1</li>");
</script>
The output of this Script will be:
<ul id="test">
<li>test1</li>
</ul>
Here in this example .append() add one extra <li>, whether .html() removes the old one with new one. This is the main difference between .append() and .html() in jQuery.

In simple words:
$('#somDiv').append('blabla')
works like this:
<div id='somDiv'>some text</div>
becomes:
<div id='somDiv'>some textblabla</div>
And innerHTML replaces the contents, so it becomes this:
<div id='somDiv'>blabla</div>

The correct syntax is
$("#somDiv").html("<span>Hello world</span>");

Related

Get <li> text number using jquery

i am trying to get li tag text value using js but i am not getting the expected output
i.e ("Pens").
I have added a code snippet.
Note - I cannot change html.
console.log(jQuery('#accordionItem li span').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>
Any thoughts on this ?
Use the text method like below:
console.log($('#accordionItem li span').text());
from what I understand you want the text of the li without the text of the span.
So you can use the replace function to do it like so:
console.log($('#accordionItem li').text().replace($('#accordionItem li span').text(), ''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>
if you want a more general solution that will get you just the text of the li without any of its children that would be a better solution:
console.log($('#accordionItem li').contents().get(0).nodeValue);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>
You seem to be selecting the <span> tag on your jQuery selector.
Although I'd suggest using the text method to achieve what you are looking for.
No jQuery needed.
Since you have an element with ID, you can access it directly, and get the node's text and simply remove any non-digit characters, and you'll be left with the numeral value you are after.
The benefit of this method is the irrelevance of the DOM structure - it will always work for that element (with that ID), but can be applied to any <li> element, regardless if it has a <span> child (or any other children)
console.log(
accordionItem.children[0].firstChild.textContent
)
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>

Removing only the outer html element from a HTML code section

I want to remove outer HTML element from a code snippet to get the content inside including other html elements.
that is,
consider the below code
<p> My Paragraph
<ul>Mylist
<li>Item1</li>
<li>Item2</li>
</ul>
</p>
I want to get the output displayed as below
My Paragraph
<ul>Mylist
<li>Item1</li>
<li>Item2</li>
</ul>
Is this possible ??
You need to use .unwrap() along with .contents() to target all the contents in it:
$('p').contents().unwrap();
Demo
ul elements are not legally allowed inside `p' elements.
you can unwrap() function to do this Refrence
In your code ul inside p will not work as expected when using
$('p').contents().unwrap();
As suggest by A.B. Use div instead of p, than try
$('div').contents().unwrap();

How to get the parent element too with getElementByClassName?

I have certainly extremely simple problem and I'm a little ashamed of not being able to solve it by myself.
HTML:
<div>
<ul class="test">
<li>1</li>
</ul>
<ul class="test">
<li>2</li>
</ul>
</div>
JavaScript:
var tests = document.getElementsByClassName('test')[0].innerHTML;
alert(tests);
jsFiddle:
Try it
Currently, the result shows me <li>1</li>.
This is not what I want. I want the result to be <ul class="test"><li>1</li></ul>.
I tried using .parent() (I can use jQuery) but it gives me all <ul> tag while I just want the first. I also know that I could use some .split() but it is surely not the adviced way.
I thought the problem might be coming from the .innerHTML, there is a function that would allow me to recover also the target element, and not just his children?
Just use outerHTML instead of innerHTML
var tests = document.getElementsByClassName('test')[0].outerHTML
Check Fiddle
You can do the same with jQuery. $.each to iterate over the elements and then use this so that it only points to that elements instead of all the elements with that class
jQuery
var $tests = $('.test');
$tests.each(function() {
console.log(this.outerHTML)
});
jQuery Fiddle

jquery replace all <ol> with <ul>

Given the following dom structure I would like to transform an ordered list to an unordered list.
<div class="wrapper">
<ol>
<li><div>foo</div></li>
<ol>
<li><div>bar</div></li>
</ol>
<li><div>batz</div></li>
</ol>
</div>
What is the best way to do this?
You should use jQuery replaceWith.
ok i had to work from the inside to the outside, only replaceWith wasn't working because it replaced only the outer tags and didn't replace the inner ones, so i solved it this way:
$($('.wrapper').find('ol').get().reverse()).each(function(){
$(this).replaceWith($('<ul>'+$(this).html()+'</ul>'))
})
if someone has a better solution i would be glad to hear it.

.prevUntil not working as expected

what am I doing wrong in this code..
I should get the class name of the previous sibling using this code.. but I am getting undefined..where am I going wrong
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JprevUntil</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
$('.clickme').live('click',function(){
alert($(this).prevUntil('li.lick').className);
});
</script>
</head>
<body>
<div>
<p id="hello">Hello World</p>
<li class="lick">hello i am li</li>
heello i am a
<p class="clickme">click</p>
</div>
</body>
</html>
you can use siblings() and attr() method, prevUnti is not what you want:
Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.
$('.clickme').live('click',function(){
alert($(this).siblings('li').attr('class'));
});
className is a javascipt core element property and cannot be used with jQuery objects, if you want to use className you can try this:
$('.clickme').on('click',function() { // you can use on(). live() is deprecated
alert($(this).siblings('li')[0].className);
});
From the prevUntil api documentation
*Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.*
You are expecting the prevUntil to stop at the li.lick but it is not included.
You can see live in this jsfiddle
Do this way:-
Refer LIVE DEMO
HTML:
<div>
<li class="lick2">hello i am li 2</li>
<p id="hello">Hello World</p>
<li class="lick">hello i am li</li>
heello i am a
<p class="clickme">click</p>
<li class="lick1">hello i am li 2</li>
</div>​
JS:
$('.clickme').one('click',function(){
alert($(this).prevAll('li').attr('class'));
});​
OUTPUT:
lick
Look what the jQuery documentation says about this:
Get all preceding siblings of each element up to but not including the
element matched by the selector, DOM node, or jQuery object.
Your element is NOT included thats why you don't get what you want.
You could try the following:
$('.clickme').live('click',function(){
alert($(this).prevAll('li.lick').get(0).className);
});
UPDATE:
Seems like what you want to achieve (getting the closest preceding sibling) can be done with that code (code taken from here):
$('.clickme').live('click',function(){
alert($(this).prevAll('li.lick:first').attr('class'));
});
FIDDLE
It's because you get a JQuery wrapped object, try :
$('.clickme').live('click',function(){
alert($(this).prev('li.lick')[0].className);
});
If you inspect your code for
$(this).prevUntil('li.lick')
You have :
-->$(this).prevUntil('li.lick'): e.fn.e.init[1]
0: HTMLAnchorElement
context: HTMLParagraphElement
length: 1
prevObject: e.fn.e.init[1]
selector: ".prevUntil(li.lick)"
__proto__: Object[0]
Your HTMLAnchorElement is a DOM object, it's here that you can retrieve your className property.

Categories

Resources