Here is my code:
$('button').on('click', function(){
$('div').after('<p>this element should be unique</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>this is a div</div>
<button>click</button>
As you see, when I click on that <button> several times, I will see multiple element which have created, like this:
<div>this is a div</div>
<p>this element should be unique</p>
<p>this element should be unique</p>
<p>this element should be unique</p>
<button>click</button>
but I want to append that <p> after <div> only if it isn't exist, otherwise I want to replace it. Anyway I want this output: (both for one time clicking and multiple times clicking)
<div>this is a div</div>
<p>this element should be unique</p>
<button>click</button>
How can I do that?
If you will have only one p
edited
$('button').on('click', function() {
if (!($('div').next('p').length)) {
$('div').after('<p>this element should be unique</p>');
}else{
$('div').next('p').html('this will replace');
}
});
You can check to see if the element exists, and if it does update the content. Something like this should work:
var index = 0;
$('button').on('click', function(){
index++;
if($('#myWrapper').length == 0) {
$('div').after('<p id="myWrapper">this element should be unique' + index +'</p>');
} else {
$('#myWrapper').html('<p>this element should be unique' + index +'</p>');
}
});
JS Fiddle example: https://jsfiddle.net/igor_9000/44mgz316/3/
Hope that helps!
Without knowing how you're generating that <p> elements, here you can check some generic solution, and implement your own logic
var text;
$('#text').on('change', function() {
text = $(this).val();
});
$('button').on('click', function() {
if ($('div').next('p:contains(' + text + ')').length) {
} else {
$('div').next('p').remove();
$('div').after('<p>' + text + '</p>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<div>this is a div</div>
<button>click</button>
Better add a wrapper, and just replace its contents:
var $target = null;
$('button').on('click', function(){
if(!$target) $target = $('<div></div>').insertAfter('div');
$target.html('<p>this element should be unique</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>this is a div</div>
<button>click</button>
Related
I'd like to update element's text dynamically:
<div>
**text to change**
<someChild>
text that should not change
</someChild>
<someChild>
text that should not change
</someChild>
</div>
I'm new to jQuery, so this task seems to be quite challenging for me.
Could someone point me to a function/selector to use?
If it is possible, I'd like to do it without adding a new container for the text I need to change.
Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.
In Javascript, the childNodes property gives you all the child nodes of an element, including text nodes.
So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this HTML:
<div id="your_div">
**text to change**
<p>
text that should not change
</p>
<p>
text that should not change
</p>
</div>
You could do this:
var your_div = document.getElementById('your_div');
var text_to_change = your_div.childNodes[0];
text_to_change.nodeValue = 'new text';
Of course, you can still use jQuery to select the <div> in the first place (i.e. var your_div = $('your_div').get(0);).
Update 2018
Since this is a pretty popular answer I decided to update and beautify it a little by adding the textnode selector to jQuery as a plugin.
In the snippet below you can see that I define a new jQuery function that gets all (and only) the textNodes. You can chain of this function as well with for example the first() function.
I do a trim on the text node and check if it's not empty after the trim because spaces, tabs, new lines, etc. are also recognized as text nodes. If you need those nodes too then simple remove that from the if statement in the jQuery function.
I added an example how to replace first text node and how to replace all text nodes.
This approach makes it easier to read the code and easier to use it multiple times and with different purposes.
The Update 2017 (adrach) should still work as well if you prefer that.
As jQuery extension
//Add a jQuery extension so it can be used on any jQuery object
jQuery.fn.textNodes = function() {
return this.contents().filter(function() {
return (this.nodeType === Node.TEXT_NODE && this.nodeValue.trim() !== "");
});
}
//Use the jQuery extension
$(document).ready(function(){
$('#replaceAll').on('click', () => {
$('#testSubject').textNodes().replaceWith('Replaced');
});
$('#replaceFirst').on('click', () => {
$('#testSubject').textNodes().first().replaceWith('Replaced First');
});
});
p {
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
**text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**also text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>
Javascript (ES) equivalent
//Add a new function to the HTMLElement object so it can be used on any HTMLElement
HTMLElement.prototype.textNodes = function() {
return [...this.childNodes].filter((node) => {
return (node.nodeType === Node.TEXT_NODE && node.nodeValue.trim() !== "");
});
}
//Use the new HTMLElement function
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#replaceAll').addEventListener('click', () => {
document.querySelector('#testSubject').textNodes().forEach((node) => {
node.textContent = 'Replaced';
});
});
document.querySelector('#replaceFirst').addEventListener('click', function() {
document.querySelector('#testSubject').textNodes()[0].textContent = 'Replaced First';
});
});
p {
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
**text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**also text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>
Update 2017 (adrach):
It looks like several things changed since this was posted. Here is an updated version
$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("change text");
Original answer (Not working for current versions)
$("div").contents().filter(function(){ return this.nodeType == 3; })
.filter(':first').text("change text");
Source: http://api.jquery.com/contents/
See In action
Markup :
$(function() {
$('input[type=button]').one('click', function() {
var cache = $('#parent').children();
$('#parent').text('Altered Text').append(cache);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">Some text
<div>Child1</div>
<div>Child2</div>
<div>Child3</div>
<div>Child4</div>
</div>
<input type="button" value="alter text" />
Just wrap the text you want to change in a span with a class to select.
Doesn't necessarily answer your question I know, but, probably a better coding practice. Keep things clean and simple
<div id="header">
<span class="my-text">**text to change**</span>
<div>
text that should not change
</div>
<div>
text that should not change
</div>
</div>
Voilà!
$('#header .mytext').text('New text here')
<div id="divtochange">
**text to change**
<div>text that should not change</div>
<div>text that should not change</div>
</div>
$(document).ready(function() {
$("#divtochange").contents().filter(function() {
return this.nodeType == 3;
})
.replaceWith("changed text");
});
This changes only the first textnode
For the specific case you mentioned:
<div id="foo">
**text to change**
<someChild>
text that should not change
</someChild>
<someChild>
text that should not change
</someChild>
</div>
... this is very easy:
var div = document.getElementById("foo");
div.firstChild.data = "New text";
You don't state how you want to generalize this. If, say, you want to change the text of the first text node within the <div>, you could do something like this:
var child = div.firstChild;
while (child) {
if (child.nodeType == 3) {
child.data = "New text";
break;
}
child = child.nextSibling;
}
$.fn.textPreserveChildren = function(text) {
return this.each(function() {
return $(this).contents().filter(function() {
return this.nodeType == 3;
}).first().replaceWith(text);
})
}
setTimeout(function() {
$('.target').textPreserveChildren('Modified');
}, 2000);
.blue {
background: #77f;
}
.green {
background: #7f7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="target blue">Outer text
<div>Nested element</div>
</div>
<div class="target green">Another outer text
<div>Another nested element</div>
</div>
Simple answer:
$("div").contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue = "The text you want to replace with"
Here is yet another method : http://jsfiddle.net/qYUBp/7/
HTML
<div id="header">
**text to change**
<div>
text that should not change
</div>
<div>
text that should not change
</div>
</div>
JQUERY
var tmp=$("#header>div").html();
$("#header").text("its thursday").append(tmp);
Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin:
$.fn.textnodes = function () {
return this.contents().filter(function (i,n) {
return n.nodeType == 3 && n.textContent.trim() !== "";
});
};
$("div").textnodes()[0] = "changed text";
Lots of great answers here but they only handle one text node with children. In my case I needed to operate on all text nodes and ignore html children BUT PRESERVE THE ORDERING.
So if we have a case like this:
<div id="parent"> Some text
<div>Child1</div>
<div>Child2</div>
and some other text
<div>Child3</div>
<div>Child4</div>
and here we are again
</div>
We can use the following code to modify the text only AND PRESERVE THE ORDERING
$('#parent').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
}).each(function() {
//You can ignore the span class info I added for my particular application.
$(this).replaceWith(this.nodeValue.replace(/(\w+)/g,"<span class='IIIclassIII$1' onclick='_mc(this)' onmouseover='_mr(this);' onmouseout='_mt(this);'>$1X</span>"));
});
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="parent"> Some text
<div>Child1</div>
<div>Child2</div>
and some other text
<div>Child3</div>
<div>Child4</div>
and here we are again
</div>
Here is the jsfiddle of it working
I think you're looking for .prependTo().
http://api.jquery.com/prependTo/
We can also select an element on the
page and insert it into another:
$('h2').prependTo($('.container'));
If an element selected this way is
inserted elsewhere, it will be moved
into the target (not cloned):
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
If there is more than one target
element, however, cloned copies of the
inserted element will be created for
each target after the first.
This is an old question but you can make a simple function like this to make your life easier:
$.fn.toText = function(str) {
var cache = this.children();
this.text(str).append(cache);
}
Example:
<div id="my-div">
**text to change**
<p>
text that should not change
</p>
<p>
text that should not change
</p>
</div>
Usage:
$("#my-div").toText("helloworld");
2019 vesrsion - Short & Simple
document.querySelector('#your-div-id').childNodes[0].nodeValue = 'new text';
Explanation
document.querySelector('#your-div-id') is used for selecting the parent (the element which text you are about to change)
.childNodes[0] selects the text node
.nodeValue = 'new text' sets text node value to "new text"
This answer is possibly inspired by Dean Martin's comment. Can't say for sure since I've been using this solution for years now. Just thought I should post this probability here because some people care about it more than the fact that this is the best solution.
Javascript approach. select the parent div and we can use the firstChild.textContent
let myDiv = document.getElementById("parentDiv");
myDiv.firstChild.textContent = "** New Text **"
Here's a recursive way:
function changeInnerText(elm,text,newText) {
if (elm == null) {
return;
}
changeInnerTextHelper(elm.firstChild, text, newText);
}
function changeInnerTextHelper(elm, text, newText) {
if (elm == null) {
return;
}
if (elm.nodeType == 3 && elm.data == text) {
elm.data = newText;
return;
}
changeInnerTextHelper(elm.firstChild, text, newText);
changeInnerTextHelper(elm.nextSibling, text, newText);
}
I'd like to update element's text dynamically:
<div>
**text to change**
<someChild>
text that should not change
</someChild>
<someChild>
text that should not change
</someChild>
</div>
I'm new to jQuery, so this task seems to be quite challenging for me.
Could someone point me to a function/selector to use?
If it is possible, I'd like to do it without adding a new container for the text I need to change.
Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.
In Javascript, the childNodes property gives you all the child nodes of an element, including text nodes.
So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this HTML:
<div id="your_div">
**text to change**
<p>
text that should not change
</p>
<p>
text that should not change
</p>
</div>
You could do this:
var your_div = document.getElementById('your_div');
var text_to_change = your_div.childNodes[0];
text_to_change.nodeValue = 'new text';
Of course, you can still use jQuery to select the <div> in the first place (i.e. var your_div = $('your_div').get(0);).
Update 2018
Since this is a pretty popular answer I decided to update and beautify it a little by adding the textnode selector to jQuery as a plugin.
In the snippet below you can see that I define a new jQuery function that gets all (and only) the textNodes. You can chain of this function as well with for example the first() function.
I do a trim on the text node and check if it's not empty after the trim because spaces, tabs, new lines, etc. are also recognized as text nodes. If you need those nodes too then simple remove that from the if statement in the jQuery function.
I added an example how to replace first text node and how to replace all text nodes.
This approach makes it easier to read the code and easier to use it multiple times and with different purposes.
The Update 2017 (adrach) should still work as well if you prefer that.
As jQuery extension
//Add a jQuery extension so it can be used on any jQuery object
jQuery.fn.textNodes = function() {
return this.contents().filter(function() {
return (this.nodeType === Node.TEXT_NODE && this.nodeValue.trim() !== "");
});
}
//Use the jQuery extension
$(document).ready(function(){
$('#replaceAll').on('click', () => {
$('#testSubject').textNodes().replaceWith('Replaced');
});
$('#replaceFirst').on('click', () => {
$('#testSubject').textNodes().first().replaceWith('Replaced First');
});
});
p {
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
**text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**also text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>
Javascript (ES) equivalent
//Add a new function to the HTMLElement object so it can be used on any HTMLElement
HTMLElement.prototype.textNodes = function() {
return [...this.childNodes].filter((node) => {
return (node.nodeType === Node.TEXT_NODE && node.nodeValue.trim() !== "");
});
}
//Use the new HTMLElement function
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#replaceAll').addEventListener('click', () => {
document.querySelector('#testSubject').textNodes().forEach((node) => {
node.textContent = 'Replaced';
});
});
document.querySelector('#replaceFirst').addEventListener('click', function() {
document.querySelector('#testSubject').textNodes()[0].textContent = 'Replaced First';
});
});
p {
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
**text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**also text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>
Update 2017 (adrach):
It looks like several things changed since this was posted. Here is an updated version
$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("change text");
Original answer (Not working for current versions)
$("div").contents().filter(function(){ return this.nodeType == 3; })
.filter(':first').text("change text");
Source: http://api.jquery.com/contents/
See In action
Markup :
$(function() {
$('input[type=button]').one('click', function() {
var cache = $('#parent').children();
$('#parent').text('Altered Text').append(cache);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">Some text
<div>Child1</div>
<div>Child2</div>
<div>Child3</div>
<div>Child4</div>
</div>
<input type="button" value="alter text" />
Just wrap the text you want to change in a span with a class to select.
Doesn't necessarily answer your question I know, but, probably a better coding practice. Keep things clean and simple
<div id="header">
<span class="my-text">**text to change**</span>
<div>
text that should not change
</div>
<div>
text that should not change
</div>
</div>
Voilà!
$('#header .mytext').text('New text here')
<div id="divtochange">
**text to change**
<div>text that should not change</div>
<div>text that should not change</div>
</div>
$(document).ready(function() {
$("#divtochange").contents().filter(function() {
return this.nodeType == 3;
})
.replaceWith("changed text");
});
This changes only the first textnode
For the specific case you mentioned:
<div id="foo">
**text to change**
<someChild>
text that should not change
</someChild>
<someChild>
text that should not change
</someChild>
</div>
... this is very easy:
var div = document.getElementById("foo");
div.firstChild.data = "New text";
You don't state how you want to generalize this. If, say, you want to change the text of the first text node within the <div>, you could do something like this:
var child = div.firstChild;
while (child) {
if (child.nodeType == 3) {
child.data = "New text";
break;
}
child = child.nextSibling;
}
$.fn.textPreserveChildren = function(text) {
return this.each(function() {
return $(this).contents().filter(function() {
return this.nodeType == 3;
}).first().replaceWith(text);
})
}
setTimeout(function() {
$('.target').textPreserveChildren('Modified');
}, 2000);
.blue {
background: #77f;
}
.green {
background: #7f7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="target blue">Outer text
<div>Nested element</div>
</div>
<div class="target green">Another outer text
<div>Another nested element</div>
</div>
Simple answer:
$("div").contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue = "The text you want to replace with"
Here is yet another method : http://jsfiddle.net/qYUBp/7/
HTML
<div id="header">
**text to change**
<div>
text that should not change
</div>
<div>
text that should not change
</div>
</div>
JQUERY
var tmp=$("#header>div").html();
$("#header").text("its thursday").append(tmp);
Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin:
$.fn.textnodes = function () {
return this.contents().filter(function (i,n) {
return n.nodeType == 3 && n.textContent.trim() !== "";
});
};
$("div").textnodes()[0] = "changed text";
Lots of great answers here but they only handle one text node with children. In my case I needed to operate on all text nodes and ignore html children BUT PRESERVE THE ORDERING.
So if we have a case like this:
<div id="parent"> Some text
<div>Child1</div>
<div>Child2</div>
and some other text
<div>Child3</div>
<div>Child4</div>
and here we are again
</div>
We can use the following code to modify the text only AND PRESERVE THE ORDERING
$('#parent').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
}).each(function() {
//You can ignore the span class info I added for my particular application.
$(this).replaceWith(this.nodeValue.replace(/(\w+)/g,"<span class='IIIclassIII$1' onclick='_mc(this)' onmouseover='_mr(this);' onmouseout='_mt(this);'>$1X</span>"));
});
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="parent"> Some text
<div>Child1</div>
<div>Child2</div>
and some other text
<div>Child3</div>
<div>Child4</div>
and here we are again
</div>
Here is the jsfiddle of it working
I think you're looking for .prependTo().
http://api.jquery.com/prependTo/
We can also select an element on the
page and insert it into another:
$('h2').prependTo($('.container'));
If an element selected this way is
inserted elsewhere, it will be moved
into the target (not cloned):
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
If there is more than one target
element, however, cloned copies of the
inserted element will be created for
each target after the first.
This is an old question but you can make a simple function like this to make your life easier:
$.fn.toText = function(str) {
var cache = this.children();
this.text(str).append(cache);
}
Example:
<div id="my-div">
**text to change**
<p>
text that should not change
</p>
<p>
text that should not change
</p>
</div>
Usage:
$("#my-div").toText("helloworld");
2019 vesrsion - Short & Simple
document.querySelector('#your-div-id').childNodes[0].nodeValue = 'new text';
Explanation
document.querySelector('#your-div-id') is used for selecting the parent (the element which text you are about to change)
.childNodes[0] selects the text node
.nodeValue = 'new text' sets text node value to "new text"
This answer is possibly inspired by Dean Martin's comment. Can't say for sure since I've been using this solution for years now. Just thought I should post this probability here because some people care about it more than the fact that this is the best solution.
Javascript approach. select the parent div and we can use the firstChild.textContent
let myDiv = document.getElementById("parentDiv");
myDiv.firstChild.textContent = "** New Text **"
Here's a recursive way:
function changeInnerText(elm,text,newText) {
if (elm == null) {
return;
}
changeInnerTextHelper(elm.firstChild, text, newText);
}
function changeInnerTextHelper(elm, text, newText) {
if (elm == null) {
return;
}
if (elm.nodeType == 3 && elm.data == text) {
elm.data = newText;
return;
}
changeInnerTextHelper(elm.firstChild, text, newText);
changeInnerTextHelper(elm.nextSibling, text, newText);
}
I have several divs with the same class names and varying IDs. The ID is not set for the text I need to target
I need to target the Telephone Call text. If the div contains that text, how do I hide the containing div
<div id="rn_FieldDisplay_155" class="rn_FieldDisplay rn_Output">
<span class="rn_DataLabel">Telephone Call </span>
<div class="rn_DataValue">No</div>
</div>
I have tried the following to no avail
<script>
$(document).ready(function() {
$(".rn_FieldDisplay > span:contains('Telephone Call')").hide ();
});
</script>
If your code is hiding the span, but not the parent div, you can target the div to be hidden using mostly the same code you already wrote.
<script>
$(document).ready(function() {
$(".rn_FieldDisplay > span:contains('Telephone Call')").parent().hide();
});
</script>
Try selecting it's child instead of the element itself :
$(document).ready(function() {
$(".rn_FieldDisplay *:contains('Telephone Call')").hide ();
});
Try with find() function
$(document).ready(function() {
$(".rn_FieldDisplay").find(":contains('Telephone Call')").hide ();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rn_FieldDisplay_155" class="rn_FieldDisplay rn_Output">
<span class="rn_DataLabel">Telephone Call </span>
<div class="rn_DataValue">No</div>
<p class="rn_DataLabel">Telephone Call </p>
</div>
Well you can try this:
if ($(".rn_FieldDisplay > span:contains('Telephone Call')").length > 0) {
$(".rn_FieldDisplay > span").hide();
}
I want to copy the text of a div to its class. I have got the code below but it copies text from all sibling div(s) but I want only current div's text to be its class.
Like the code below will copy "I am alex How are you" as a class for both divs below code, what I want the 1st div should only have class "I am alex" and likewise next class should only have a class "How are you" .
<div class="someText">I am alex</div>
<div class="someText">How are you</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js" type="text/javascript"></script>
<script>
var classes = $(".someText").text().replace(/[, -- .]/g," ");
$(".someText").addClass(classes);
</script>
It's a very odd requirement, but you can achieve it by passing a function to addClass(), like this:
$('.someText').addClass(function() {
return $(this).text();
});
.am {
color: blue;
}
.are {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someText">I am alex</div>
<div class="someText">How are you</div>
You would need to loop through each div.
$(function() {
$('div.someText').each(function() {
var classes = $(this).text().replace(/[, -- .]/g, " ");
$(this).addClass(classes);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someText">I am alex</div>
<div class="someText">How are you</div>
This what you wanted?
var divs = $(".someText");
for (var i = 0; i < divs.length; i++) {
$(divs[i]).addClass($(divs[i]).text().replace(/[, -- .]/g," "));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someText">I am alex</div>
<div class="someText">How are you</div>
I wont to change order of paragraphs(the one clicked by user should be at the top). I came up with this:
<div>
<p>11111111</p>
<p>22222222</p>
<p>33333333</p>
</div>
$("p").click(function(){
var a = $(this).index();
if (a != 0) {
$(this).clone().prependTo("div");
$(this).remove();
}
})
but it works just "once".
http://plnkr.co/edit/6VlWbIlGi7fDBv6d0WT2?p=preview
You're not very far off, it's actually easier than that: Just prepend the element to its own parent with prependTo:
$("p").click(function() {
var $this = $(this);
$this.prependTo($this.parent());
});
<div>
<p>11111111</p>
<p>22222222</p>
<p>33333333</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you want, you don't even really need jQuery for it:
$("p").click(function() {
this.parentNode.insertBefore(this, this.parentNode.firstChild);
});
<div>
<p>11111111</p>
<p>22222222</p>
<p>33333333</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can use .insertBefore(); and you need to jQuery event delegation as well
$("div").on('click','p:not(:nth-child(1))',function(){
$(this).insertBefore('p:nth-child(1)');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>11111111</p>
<p>22222222</p>
<p>33333333</p>
</div>