Selectively getting text from <div> - javascript

<div class="myDiv">
<p>I need get<strong>this</strong>
<a title="And this" href="#">but not this</a>
</p>
<p>And also<strong>This</strong>
<a title="And this" href="#">but not this</a>
</p>
</div>
How do I grab everything in p tag except for the text in nested a tag. And also I need to get values for "title" attirbute for tag a?

Using http://api.jquery.com/replaceWith/
Creates a clone
Replaces the a tags with their title attributes
Calls text() on the cloned node
http://jsfiddle.net/mendesjuan/cBejv/2/
var clone = $('.myDiv p').clone();
clone.find('a').replaceWith(function() {
return this.getAttribute('title');
})
console.log(clone.text());
Outputs
I need get this
And this And also This
And this

How about this:
$('.myDiv a').text('');
$('.myDiv p').each(function() {
console.log($(this).text()+$('a',this).attr('title'));
});
jsFiddle example.

Something like this would work. There may be a much better way to do this, but this was the first thing to come to mind.
var $clone = $('.myDiv').clone();
$clone.find('a').remove();
$('#output').append($clone.text());​
Make sure you add an element with id="output" to see the results.

Related

How to get parent element html but not children tags?

I am not sure I gave correct title to my question but I want to ask to do something like:
I want to get HTML content of parent element. By doing this, this will also include HTML tags of children element but I don't want that. I just want children HTML.
For Example:
<div class="test"> This is content of div
<p class="boring_class" style="borinhdlfj"> This is paragraph<br> content.<span><i>As you<br> can</i></span> see I have added <br> tag</p>
</div>
from above example If I use .text() jquery method to get div content I will get text only but not <br> tag. But if I use .html() jquery, this will also include <p class="boring_class" style='dflkdjf'>....</p> but I don't want that.
I just want html of children element which is:This is paragraph<br> content.As you can see I have added <br> tag.
How can I achieve that?
Final output should look like:
This is content of div This is paragraph <br> content.As you can see I have added <br> tag
As one possible interpretation of the question:
Get html of all children, including text [not in a children nodes]
You can use .contents() to include the text nodes of the parent (the parts that aren't in tags, eg "This is content of div") then loop through those to get either text or html depending on where it is, giving:
var output = $(".test").contents().map((i, e) => {
if (e.nodeType == 3)
return $(e).text();
return $(e).html()
})
.toArray()
.join(" ");
console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"> This is content of div
<p class="boring_class" style="borinhdlfj"> This is paragraph<br> content.As you can see I have added <br> tag</p>
</div>
Note this includes all whitespace (newlines) which were not included in the question's example output, so you may need to remove these for an exact match.
You can accomplish this in regular javascript by using innerHTML as shown below.
For more info, see: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
const list = document.getElementsByClassName("test")[0];
const inner = list.innerHTML;
const noP = inner.replace(/<p[^>]*>/g, "").replace(/<\/p[^>]*>/g, "").replace(/\n/g,'');
console.log(noP);
<div class="test"> This is content of div
<p class="boring_class" style="borinhdlfj"> This is paragraph<br> content.As you can see I have added <br> tag</p>
</div>

How to append just before the end of the BODY tag using JQuery [duplicate]

I have this HTML:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
</div>
and want to add more divs after the strong element to result:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
<div> ... </div>
<div> ... </div>
<div> ... </div>
</div>
I am trying this:
var row_str = '<div>content here</div>';
$('#region_North_America div:last').html(row_str);
However, there is no change to the html. This is probably so since there is no div within the element selected.
I know that the js is making it to this code because I can print the content of row_str to the console.
So, how can I get to the end of that container element to add the new items?
Thx.
Try:
$("#region_North_America").append(row_str);
using append().
Or:
$("<div>content here</div>").appendTo("#region_North_America");
To create the element on the fly, and place it in the document.
Using the appendTo method.
Your code will just place html in the last div within #region_North_America. Use the append function.
$("div.region-list").append(row_str);

Jquery remove everything except for bolded

I have html like this:
<div id="divTestArea1">
<b>Bold text</b>
<i>Italic text</i>
<div id="divTestArea2">
<b>Bold text 2</b>
<i>Italic text 2</i>
<div>
<b>Bold text 3</b>
</div>
</div>
and I would like to remove all elements that aren't bold. I've tried with this code:
$('*:not(b)').remove();
and a couple other variations but they all either error out or remove everything. btw, are jquery selectors and jsoup selectors 100% compatible? I'd like to use the answer to this in jsoup as well.
Your current code removes the document <body> as well as all <div>s which contain the <b> tags. If you only want to save the bold text then Shih-En Chou's solution works well. If you want to save the <div> structure that the <b> tags are in as well you could do this:
$("body *:not(div, b)")​​​​.remove();​
DEMO
My solution:
I clone <b> and save it into memory.
->Remove all
-> insert <b> into <body>
here is my code:
http://jsfiddle.net/sechou/43ENq/
$(function(){
var tmpB = $("b").clone();
$('body').remove();
$("body").append(tmpB);
});​
Move all elements in #divTestArea2 as it is a div and will be removed as well to #divTestArea1, then filter out anything that is'nt a <b> and remove it :
$("#divTestArea1").append($("*", "#divTestArea2")).find('*').filter(function() {
return this.tagName !== 'B';
}).remove();
FIDDLE
The above keeps the #divTestArea1 element intact, to remove everything but the <b> elements, something like :
$('body')​.append($('b'))​.find('*')​.not('b')​.remove();​
FIDDLE
I prefer .detach().
var $body = $("body");
var $b = $("b", $body).detach();
$(":not(b)", $body).remove();​​​​​​​​​​​
$body.append($b);
This way you don't need to either move or clone anything to overcome the problem of the deletion of the objects wrapping your <b/> elements.
(demo)
Try this:
// Find all the <b> tags and unwrap them so they all become siblings and finally
// remove non <b> siblings
$('body').find('b').unwrap().siblings('*:not(b)').remove();
Demo: http://jsfiddle.net/3f2Hu/

Data only to click the div

Good morning, everyone.
I have a doubt. I have a list of div. textarea with text inside it and inside. text for a button event. Want to get only the data from the textarea div that the person clicking the button.
I would be very grateful for the help. thanks
Example code.
<div class="text">
<textarea id="texts" class="texts" rows="5" cols="45" name="textarea"> </ textarea>
<div class="bt" id="1234556">
<div class="button"> Send </div>
</div>
</div>
$('.button').click(function() {
var text = $('#texts').val();
// do something with text
alert(text);
});
Working demo at http://jsfiddle.net/PPcxm/
As long as you have the same structure (and presuming you have more than one example on the page as the button is a class and textarea is an id, the following would work:
$(".button").click(function()
{
var text = $(this).parent().prev().val();
});
Since you have a list of div.text your best bet is to query based upon the structure of your DOM.
$(".button").click(function() {
var $textArea = $(this).parents(".text").find(".texts");
//Do something with $textArea.Val();
});
What we simply do is call .parents() on the current div.button which will allow us to get the div.text element. From there you can simply find your textarea.texts element and get the corresponding value.
Code example on jsfiddle.

Very basic question about parent() and prev() in jQuery

I am handling a hyperlink's click event with a JavaScript function. I want to retrieve data from the hyperlink.
The page looks like this:
<div class="div1">
<div title="Title 1" class="div2">
<p class="p1"><a class="linkJs">The link in question</a></p>
</div>
</div>
<div class="div1">
<div title="Title 2" class="div2">
<p class="p1"><a class="linkJs">The link in question</a></p>
</div>
</div>
And the JavaScript something like this:
$(function() {
$('a.linkJs').click(function(){
value=$(this).parent().prev().text();
alert(value);
});
});
What I want to have is the value of the TITLE in the div2. By clicking the first link I get : Title 1. And by clicking on the 2nd: Title 2.
This must be very very basic but I just can't find my answer anywhere.
Thanks.
You want to use closest
var value = $(this).closest('div').attr('title');
Your problem is that the <p> tag is not a sibling to the <div> but a child, so you would have to do parent() twice - there's no need, though, as the closest function is a handy shortcut. Also, the text() function returns the pure text contents inside the tag, if you want the title attribute of the tag you need to use the attr function.
You can find it with the closest method:
$('a.linkJs').click(function(){
value=$(this).closest('div').attr('title');
alert(value);
});
try using the closest() method: http://api.jquery.com/closest/
Get the first ancestor element that
matches the selector, beginning at the
current element and progressing up
through the DOM tree.
$(function() {
$('a.linkJs').click(function(){
value=$(this).closest(".div2").attr("title");
alert(value);
});
});
var value = $(this).closest('.div2').attr('title');
Instead of using div, .div2 may be a more appropriate selector because there may be other div elements inside div.div2.
Not very pretty, but this should work too.
$(function() {
$('a.linkJs').click(function(){
value=$(this).parents()[1];
alert($(value).attr('title'));
});
});

Categories