Get text from all spans in div using jQuery - javascript

I'm dynamically adding span elements to a div. I want to retrieve the text from all the span elements in the div at a later stage. How do I do this? I'd like to use jQuery, but Javascript is fine I guess.
Section of Javascript creating the span elements:
var x = ui.item.value;
var span = document.createElement("span");
span.innerHTML=" "+x+"";
$("#selected").append(span);
This is inside an on click event.
The div is called "selected".

You can try something like this:
var txt= "";
$("#selected span").each(function(){
txt += $(this).text();//here you get the values from each span inside selected element
});
$("body").append(txt);//here append the collected text inside e.g. body
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selected">
<span>1</span>
<span>1</span>
<span>1</span>
<span>1</span>
</div>

No need for a .each() or any other loop. Just calling .text() will be enough since, according to the JQuery docs, it:
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
So:
$("#selected").click(function() {
var text = $(this).find("span").text();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="selected">
<span>1</span>
<span>2</span>
<span>3</span>
</div>

Related

Resolved: How to select all nodes after a specific node

I have the following HTML elements:
<p>Content here</p>
<div class="pagebreak"></div>
Sometext
<span style="somestying"><strong>Title</strong></span>
...and many more content.
Using below JQuery code, I'm trying to select all nodes after the the node with class pagebreak
var findPagebreak = $(currentPagina[0]).find('.pagebreak');
var nextContent = $(findPagebreak).nextAll();
But the variable nextContent only contains node:
<span style="somestying"><strong>Title</strong></span>
I would like to take select the text nodes and all html elements after the div with pagebreak class.
Anyway I could do this?

Adding div tag below another div tag

I have a div tag with class divstudent, lets say this is div1 tag. Now I want to create another div tag div2 dynamically below this div1 tag, not inside of the div1 tag. I want to create outside of div1 tag using javascript. How can I do that?
"div1"
<div class="divstudent"></div>
<!-- i want to be like this -->
<!-- "div1" -->
<div></div>
<!-- "div2" -->
<div></div>
<!-- "div3" -->
<div></div>
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
Try something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Divs creator</title>
<script type="text/javascript">
window.onload = function () {
var divReference = document.querySelector('.divstudent');
var divCounter = 0;
divReference.addEventListener('click', function () {
var divToCreate = document.createElement('div');
divToCreate.innerHTML = ++divCounter;
divReference.parentNode.appendChild(divToCreate);
}, false);
}
</script>
</head>
<body>
<div class="divstudent">
<input type="button" value="add div below divstudent">
</div>
</body>
</html>
Since this is tagged jquery, just use .after()
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
There are many ways to do this. One significant difference in methods is if you choose to create the elements first using Document.createElement() and then insert the elements, or create and insert the elements in one step using one of the methods that allows you to insert HTML text.
Because it is simpler, but not necessarily better, the examples below show creating and inserting the two <div> elements in a single step using methods that allow inserting HTML text into the DOM.
JavaScript:
One is to use insertAdjacentHTML() and specify that it is to be inserted afterend of the element you are using.
document.querySelector() is used to find the first <div class="divstudent">. Then insertAdjacentHTML() is used to add the additional <div> elements. Element.removeAttribute() is then used to remove the class="divstudent". Note: if we had just wanted to set teh class to something different, even '', then we could have used Element.className.
NOTE: In this answer, text identifying each <div> has been added to the <div>s so there is something visible in the examples in this answer.
//Find the first <div class="divstudent"> in the document
var studentDiv = document.querySelector('div.divstudent');
//Insert two new <div> elements.
studentDiv.insertAdjacentHTML('afterend','<div>2</div><div>3</div>');
//Remove the class="divstudent"
studentDiv.removeAttribute('class');
<div class="divstudent">1</div>
jQuery:
While your question is tagged jQuery, a comment you posted implies you are just using JavaScript. Thus, I am not sure if jQuery works for you.
If you want to use jQuery, then you can use .after() to add the <div> elements. You can then use .removeAttr() to remove the class="divstudent".
// Get the first <div class="divstudent">.
// Store it in a variable so we only walk the DOM once.
var $studentDiv = $('div.divstudent').eq(0);
//Add the two new <div> elements
$studentDiv.after('<div>2</div><div>3</div>');
//Remove the class="divstudent"
$studentDiv.removeAttr('class');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divstudent">1</div>
You create a new div (in js), then just append your newDiv, after the target div. Something along the lines of in vanilla js:
// Create your new div
var newDiv = document.createElement("div");
newDiv.innerText = "New Div!";
// Grab the div you want to insert your new div after
var target_div = document.querySelector("div.divstudent");
// Insert newDiv after target_div (before the thing after it)
target_div.parentNode.insertBefore(newDiv, target_div.nextSibling);

Jquery remove element from var

I have a page with a parent div and several child divs. These are generated dynamically. I need to save the structure (html code) of all the child divs in my database, so I get the html content using .html().
But before I save the content in db, I need to remove one or more child divs. (But these divs will still need to be on the browser page)
How do I use the remove method with the selector (in this example I need to remove child3) on the output of .html()
<div id="graph-parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
</div>
var htmlContent = $( "#graph-parent" ).html();
how do I remove child3 from htmlContent?
Simply clone the element and operate on that:
var clone = $('#graph-parent').clone();
clone.find('#child3').remove();
var htmlContent = clone.html();
I think you need something like this:
http://jsfiddle.net/glegan/65QPV/
var clone = $('#graph-parent').clone();
clone.find('#child1').remove();
clone.find('#child5').remove();
var htmlContent = clone.html();
alert(htmlContent);

jquery changing clone style changes original style

I am trying to add change the inline-style property of my html. For this, I cloned a div and append it to another div. I am also trying to display the HTML contents in textarea after stripping the inline-style. Here's my code
//Store html in temp div
$("#html_code").clone().appendTo("#temp_html");
//remove style attribute
$("div.animation-1 span.front").removeAttr('style');
//clone this and attach to textarea
var html_extracted = $("#temp_html").clone().html();
$("#show_html").text(unescape(escape(html_extracted)));
Here is the #html_code:
<div id="html_code">
<!--HTML Code-->
<div class='animation-1'>
<span id="box" class='letter hidden'>
<span class='back'>Android</span>
<span class='front'>T</span>
</span>
</div>
</div>
Here is the #temp_html:
<!--Stores cloned html to remove its style-->
<div id="temp_html"></div>
Here is the #show_html:
<!-- HTML Code display -->
<div id ="html-code-area" class="codearea">
<textarea id="show_html" cols="58" rows="20">
HTML will be displayed here
</textarea>
</div>
But when the clone is changed, it changes the original too. Is there a way to change the clone only without changing the original?
Also, the text in textarea keeps adding the same code again and again. How can I replace everything in the textarea with new contents?
I checked your code in a fiddle, - it works as expected with clone(), except that you remove the style attr from both nodes. You should select only the temp html:
$("#temp_html div.animation-1 span.front").removeAttr('style');
and about replacing the text in the textarea - you need to empty #temp_html before doing a new copy, like this:
$('#temp_html').empty();
The text inside #show_html is always replaced, it's just that #temp_html had several nodes attached.
here's the new fiddle: http://jsfiddle.net/WdTum/3/

Replace content of header tag based on its own existing content

dI have a pre-existing block of html I need to alter using jQuery. The HTML looks as follows:
<div class="main">
<div class="wms-column wms-column-nav">
<div class="wms-column-nav-body">
<div class="section">
<h3>Recent News</h3>
<ul class="other">
<li>Something</li>
</ul>
</div>
</div>
</div>
</div>​
I need to target the H3 and change its inner text. However, with no IDs, targeting it with selectors is tricky. There are many other H3 tags through their site that cannot be changes, but have the same selector path. How can I target this H3 based on its content, and then change it? I'd prefer a method that inserts html and not text, as some special characters are going to be used.
Thanks!
In vanilla Javascript :
var elements = document.getElementsByTagName('h3');
for (var i=elements.length; i-->0; ) {
var element = elements[i];
var text = element.textContent || element.innerText;
if (text=='Recent News') {
element.innerHTML = 'some new text';
}
}
Demonstration
Using jQuery:
$('h3') will select all of the header tags. You can address them individually: $('h3').eq(0) $('h3').eq(1) etc.
You can also loop through them easily:
$('h3').each(function() {
alert(this.text()) <-- "this" will point to the current item in the loop.
})
Inside the loop you can access any of the current item's content, properties or attributes. You can base your logic on this accordingly.

Categories

Resources