How do I turn this:
<a class="link">
<p class="paragraph">This is some text</p>
<p class="paragraph">This is some more text</p>
<p class="paragraph">And some more</p>
</a>
into this:
<a class="link">
This is some text This is some more text And some more
</a>
with jQuery. I tried using append and merge but I just can't figure it out.
Since the text method returns the text content of an element and it's descendants, you can just use that:
var link = $("a.link");
link.text(link.text());
From the docs:
Get the combined text contents of each element in the set of matched
elements, including their descendants.
Here's a working example.
Update (see comments)
In the case that this needs to apply to multiple .link elements, you can use each:
$("a.link").each(function() {
$(this).text($(this).text());
});
This will work:
$("a.link").text(function(i,text){
return text;
});
And yet another way (not tested):
// you can optionally filter to
// only p elements too with
// .children("p")
$("a.link").children().contents().unwrap();
Here's another variation of the second:
$("a.link p").contents().unwrap();
Edit: Just a note for clarity:
All of these solutions work on multiple elements. The first solution is a relatively uncommon syntax that can be used on most jQuery setter functions. It runs the callback on each matched element and sets the value of the property/attribute to the value returned from the callback.
try this
$(document).ready(function(){
var concatText = "";
$("p.paragraph").each(function(){
concatText = concatText + " " + $(this).text()
});
$("a.link").html(concatText);
});
Related
I know this has been extensively answered but alas I have had no luck with previous code.
So I want to remove all the span elements in this div element when the user onclicks a button.
THE HTML
<div id="sequence-label" class="scrollingDiv" style="visibility: hidden;">
<li>H :</li>
<span class="spanUnselected">T</span>
<span class="spanUnselected">F</span>
<span class="spanUnselected">G</span>
<span class="spanUnselected">Q</span>
<span class="spanUnselected">G</span>
</div>
**THE JS **
$('#sequence-remove-pdb').click(sequenceRemovePdb);
function sequenceRemovePdb() {
document.getElementById("sequence-label").style.visibility = "hidden";
workspaceSideChain();
var mySeq = document.getElementById("sequence-label");
}
Things I have tried
Tried to remove all the elements as children of sequence-label
mySeq.empty();
Tried to remove by class selected
mySeq.remove(".spanUnselected");
Tried to remove by firstChild Elements
while (mySeq.firstChild) {
mySeq.removeChild(mySeq.firstChild);
}
Tried to remove by childNodes also over how many elements are in sequence-label and still nothing.
Any ideas?
The Problem
You're mixing jQuery and vanilla javascript in a way that does not work.
Specifically, you're getting an element in vanilla javascript here:
var mySeq = document.getElementById("sequence-label");
Then you are trying to remove elements using jQuery:
mySeq.empty();
and
mySeq.remove(".spanUnselected");
The Solution
The solution is simple enough. Get the element as a jQuery object first, then your functions will work:
var mySeq = jQuery("#sequence-label");
// Then act on it with jQuery as you see fit.
mySeq.find('.spanUnselected').remove();
Also, be sure your event bindings take place inside of a document ready:
jQuery(function($) {
$('#sequence-remove-pdb').click(function() {sequenceRemovePdb;});
});
I might be missing the point but to completely empty the item this might work:
document.getElementById("sequence-label").innerHTML = "";
It will empty out all the children (actually everything) from inside the "sequence-label" element.
Try this code :
$('#sequence-remove-pdb').click(function(){
$('span.spanUnselected').remove();
});
HTML :
<div id="sequence-label" class="scrollingDiv">
<li>H :</li>
<span class="spanUnselected">T</span>
<span class="spanUnselected">F</span>
<span class="spanUnselected">G</span>
<span class="spanUnselected">Q</span>
<span class="spanUnselected">G</span>
</div>
The remove( expr ) method removes all matched elements from the DOM.
This does NOT remove them from the jQuery object, allowing you to use
the matched elements further.
JSFIDDLE LINK
I have this HTML:
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
I only want to replace Orange (and the space after it). Using .text() won't work because it selects the whole strong.
How do I do this?
This is harder to do with jQuery than with the native DOM, so if you're using jQuery, you're going to have to convert the element to the native DOM using jQuery's array indexing.
Basically, what we need to do is change the first text node. jQuery isn't really good with text nodes, which is why we use the DOM here:
//This gets the div.test element using jQuery:
var testDiv = $("div.test");
function changeColor(color) {
/* The following function changes the value of the first text node within testDiv: */
//This converts testDiv from a jQuery element to a regular DOM element. This is because jQuery isn't really meant to be handling stuff like text nodes, so doing this with the regular DOM will just be much easier.
var domElement = testDiv[0];
//Now, just change the value of the first text node:
domElement.childNodes[0].nodeValue = color;
}
//Now, as you can see if you click div.test, we can replace the color mentioned in div.test using changeColor():
testDiv.click(function() {
changeColor("Blue ");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
You should use native DOM methods. In your case the simples thing is just change nodeValue property of the first childNode element (which you know is going to be TextNode element):
var el = $('.test');
el[0].childNodes[0].nodeValue = 'Green ';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
or if you want you can grab text node with jQuery's $.fn.contents method:
var el = $('.test');
el.contents()[0].nodeValue = 'Green ';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
If you are using jquery, here is the solution
$('.test').html(function(){
return $(this).html().replace('Orange ','');
});
Find the fiddle here: https://jsfiddle.net/MasoomS/xff6dw1t/
Used data attribute to refine the code and to use it for multiple strings
HTML:
<div class="test" data-replace="Orange ">Orange <span class="is">is</span> my favorite color.</div>
<div class="test" data-replace="Green ">Green <span class="is">is</span> my next favorite color.</div>
JQUERY:
$('.test').html(function(){
return $(this).html().replace($(this).data('replace'),'');
});
document.getElementsByClassName("test")[0].childNodes[0].nodeValue = "Black";
Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.
you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..
Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}
Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element
For example I have a list title like this: <li id="example"> title </li>. And here is where I want it to be "appended to" on a click of a button: <ol id="playlist"> </ol>
Here is the button: <span onClick="Button();"> Button </span>
Here is the function:
Button=function() {
$('#playlist').append('#example');
}
I just don't see why it doesn't work I mean when I make the .append('title') - so just plain text - it will add that text to the tag but when I try to append a whole tag through the ID it doesn't? It instead appends "#example" which isn't what I want. I'm sorry I am still trying to grasp this language however, I have honestly searched and scouted the whole internet to try find an anwser to this.
Try this:
$('#playlist').append($('#example'));
Fiddle
Update:
You can use the clone() method, try this:
$('#example').clone().attr('id', 'something').appendTo($('#playlist'))
Fiddle
You need to append the whole li, so your solution would be:
function Button() {
var $li = '<li id="example"> title </li>';
$('$playlist').append($li);
}
.append( content [, content] )
content: DOM element, HTML string, or jQuery object to insert at the
end of each element in the set of matched elements. ...
jQuery is assuming that you are appending the HTML string #example literally. Use one of the the other two options e.g.:
$('#playlist').append($('#example')); // append a jQuery object
For the sake of completeness:
$('#playlist').append(document.getElementById('example')); // append a DOM element
I have the following code..
<span class="under">
texthere
<ul class="list">
<li> list text here</li>
</ul>
</span>
When i run $(".under").text() I get "textherelist text here" .
I've tried $(".under :not(.list)").text() and get underfined.
I also dont get the correct output for $(".under").not(".list").text()
So my last attemp was $(".list").parent().text()
which results in textherelist text here
Where am i going wrong with something so simple?
p.s. doesn't have to be jQuery can be JavaScript if its simpler.
Wanted result: texthere
So I'm guessing you're after the text : texthere ?
var elem = $(".under").clone(),
text = $.trim(elem.children().remove().end().text());
FIDDLE
Clone the element, remove all children elements and get the remaining text.
From the docs:
Description: Get the combined text contents of each element in the set
of matched elements, including their descendants.
So yes, that behavior is expected.
You can try this to get only the immediate text node of a selector:
$('.under').contents().filter(function(){ return(this.nodeType == 3); }).text()
Explanation:
.contents() (docs) returns the children of a selector, including textnodes
Description: Get the children of each element in the set of matched
elements, including text and comment nodes.
.filter() takes a callback to return only things you need, based on this, you are only taking those with nodeType == 3, which is a text node.
http://jsfiddle.net/R4Pzf/
Here you go:
var text = $('.under').contents(':not(.list)').text();
Example:
http://jsfiddle.net/ak4FU/1/